Dave Ryan Dave Ryan - 1 month ago 8
C# Question

C# DirectoryNotFoundException was unhandled in Windows 10 machine

C# application.exe not working in Win10,but it worked on my Win7. I tried to debug in Win10 it shows me this error which is correct in win7.

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

string fullComputerName = Environment.MachineName;

//Create a Folder Path
string createFolderPath = @"C:\\Users\\" +fullComputerName+"\\Documents\\Cheques";

//Create a File Inside of a Folder
string createTxtFile= createFolderPath + "\\ChequeForDeposit.TXT";

try
{
if(!Directory.Exists(createFolderPath))
{ return; }
Directory.CreateDirectory(createFolderPath);
}
catch { }
finally { }

if(!File.Exists(createTxtFile))
{ File.Create(createTxtFile); }//The error is here
}
}
}


when i check in my win7 pc, it creates a folder and a text file. But not in Win10. it is so strange.

Answer

Your try/catch does not ensure that directory folder will exist (may generate an exception when you try to create the folder). So before creating the file, check immediately folder is exists. Your condition is incorrect. If folder not exists then you should return, otherwise create.

 try
 {
  if(Directory.Exists(createFolderPath) && !File.Exists(createTxtFile))
    { 
       File.Create(createTxtFile);   
    }
}

Also check the permission issue. e.g. Check the permissions for the desktop folder. In Windows Explorer right click on the desktop folder, select properties and there go to the security tab. You should have write permission for that folder.