I know that there are restrictions to file operations, but SpecialFolder.LocalApplicationData
is supposed to be for application use.
string _myFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyFile.txt"); //Line1
Console.WriteLine(_myFilePath); //Line2
Console.WriteLine(File.Exists(_myFilePath)); //Line3
Console.WriteLine(File.Create(_myFilePath)); //Line4
This is the console output:
The program stops at the 4th line and VS 2022 shows this error:
How can I create or delete files/folders in SpecialFolder.LocalApplicationData
? Or which folder is recommended for this kind of file/folder operations?
CodePudding user response:
Using Windows 11, VS 2022 17.2.0 Preview 5.0 and NET 6.0 without administrator privileges:
Your code worked fine for me.
Output:
C:\Users\Edgar\AppData\Local\MyFile.txt
False
System.IO.FileStream
But here is my suggestion:
Check the ACLs of your directory: Is your account permitted for creating new files?
(Right-click the directory -> Properties -> Security -> Select your own user and check your permissions.)
Usually you should not create files directly under your %localappdata%
directory.
If you need a temp-file, I would recommend to use Path.GetTempFileName()
for getting a unique file name.
If you want to store files for a longer time, then I would recommend to create a directory for your application in %localappdata%
and save the files there.
Sample:
string myApplicationDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MyApplication");
string myApplicationFile = Path.Combine(myApplicationDirectory, "myFile.txt");
if (!Directory.Exists(myApplicationDirectory)) {
Console.WriteLine($"Creating directory: {myApplicationDirectory}");
Directory.CreateDirectory(myApplicationDirectory);
}
File.Create(myApplicationFile);
Console.WriteLine($"File created: {myApplicationFile}");
Output:
Creating directory: C:\Users\Edgar\AppData\Local\MyApplication
File created: C:\Users\Edgar\AppData\Local\MyApplication\myFile.txt