Edit: I noticed this doesn't happen when I just do: File.WriteAllText(@"C:\Users\(usr)\Documents\Test\Data\test.txt", "0");
without Globals.dmp
so evidently it must be something with Path.Combine()
I tried various variations of the composition but with same results.
I want to create a folder and a text file in my c# program made with Visual Studio. What I'm doing is having a check at Form Load to see if the file exists, and if it does not, create the file.
I'm doing it like this:
if(!File.Exists(Globals.dmp))
{
File.Create(Globals.dmp);
File.WriteAllText(Globals.dmp, "0");
}
The composition of globals.dmp
is the following:
public static string dmp = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Constants.dmp);
While Constants.dmp
is like this:
public static string dmp = @"Test\Data\test.txt
This should work, but when I try to run it, Visual studio reports: System.UnauthorizedAccessException: 'Access to the path 'C:\Users\(usr)\Documents\Test\Data\test.txt' is denied.'
The line that fails is: File.Create(Globals.dmp);
I tried putting File.SetAttributes(Globals.dmp, new FileInfo(Globals.dmp).Attributes | FileAttributes.Normal);
above File.Create
but the same thing happens. Any insight is greatly appreciated.
Run your visual studio as administrator and see it works or not.
I solved the problem by adapting PathCombineAndCanonicalize1()
from the second solution in this question
What I did is:
public static string PathCombineAndCanonicalize1(string path1, string path2)
{
string combined = Path.Combine(path1, path2);
return combined;
}
public partial class ProgramDirectories
{
public static string directory = @"DillData\";
public static string documentspath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
public static string pathforfiles = PathCombineAndCanonicalize1(documentspath, directory);
public static string sps = PathCombineAndCanonicalize1(pathforfiles, Constants.sps);
}
With Constants.sps="text.txt";
And then I could easily do:
if (!Directory.Exists(ProgramDirectories.pathforfiles))
{
Directory.CreateDirectory(ProgramDirectories.pathforfiles);
}
if(!File.Exists(ProgramDirectories.sps)
{
File.WriteAllText(ProgramDirectories.sps, "0");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.