Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

file-io

I am creating a standalone application that will be distributed to many users. Now each may place the executable in different places on their machines.
I wish to create a new file in the directory from where the executable was executed. So, if the user has his executable in :

C:\exefile\

The file is created there, however if the user stores the executable in:

C:\Users\%Username%\files\

the new file should be created there.

I do not wish to hard code the path in my application, but identify where the executable exists and create the file in that folder. How can I achieve this?

like image 409
darnir Avatar asked Aug 15 '12 09:08

darnir


2 Answers

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.

like image 171
Tigran Avatar answered Sep 21 '22 03:09

Tigran


Just use File.Create:

File.Create("fileName");

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

like image 42
Saeed Amiri Avatar answered Sep 19 '22 03:09

Saeed Amiri