C# File Handling: Create file in directory where executable exists

Never create a file into the directory where executable stays. Especially with the latest OSes available on the market, you can easily jump into the security issues, on file creation. In order to gurantee the file creation process, so your data persistancy too, use this code:

var systemPath = System.Environment.
                             GetFolderPath(
                                 Environment.SpecialFolder.CommonApplicationData
                             );
var complete = Path.Combine(systemPath , "files");

This will generate a path like C:\Documents and Settings\%USER NAME%\Application Data\files folder, where you guaranteed to have a permission to write.


Just use File.Create:

File.Create("fileName");

This will create file inside your executable program without specifying the full path.


You can get the full path to your new file with:

string path = Path.GetDirectoryName(Application.ExecutablePath) + "\\mynewfile.txt" 

Tags:

C#

File Io