zrubi zrubi - 2 years ago 116
C# Question

avoid overwriting of file and content with each run or request with executable directory

Hello I’m trying to create directory folder with text document for my windows form application executable. Now I must make it available locally for other users.

I'm doing it this way:

string dir = "%ProgramData%\\MyAppName\\doc.txt";
if (!Directory.Exists(dir))
var stream = File.CreateText(dir);

and here is my access path from executable directory inside the code:

const string mypath = (@"%ProgramData%\MyAppName\doc.txt");

On the one stage of implementation I have also separate creation of document, but I almost sure that has no connection with problem, because creates it once and never overwrites if file exist, keeps content of text document with each new run of program, adding of data or request to it. Only if I delete it by hand, in this case creates new one:

if (File.Exists(mypath))

and works perfect with local path to debug folder like this:

const string tetdb = ("doc.txt");

So code for executable must work same way, if directory, folder, file with content exist don't do nothing with it. But with code above, it rewrites everything with every request to it, not only with new run of program, with folder, text document and content inside.

but must be as follows: if folder is created once, if directory, file, document exist, no netter with code of executable, or with press enter, or it was already there. keep content inside the text document with every start of program or request to it of adding to it.

I've tried create only folder to executable path, to create text document separately as it shown above, but I got same result. So how to avoid this problem, what I'm doing wrong?

Answer Source

The test for !Directory.Exists is the cause of your problem.
You pass a filename to the method, thus the method returns false (a directory with that name doesn't exist). This means that you always enter the if and calling File.Create over an existing file overwrite the content of the file

string file = "%ProgramData%\\MyAppName\\doc.txt";
if (!Directory.Exists(Path.GetDirectoryName(file)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download