[英]Why can't I create a file in LocalApplicationData? C# , VS 2022, Windows 11
I know that there are restrictions to file operations, but SpecialFolder.LocalApplicationData
is supposed to be for application use.我知道文件操作有限制,但
SpecialFolder.LocalApplicationData
应该供应用程序使用。
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:这是控制台 output:
The program stops at the 4th line and VS 2022 shows this error:程序在第 4 行停止,VS 2022 显示此错误:
How can I create or delete files/folders in SpecialFolder.LocalApplicationData
?如何在
SpecialFolder.LocalApplicationData
中创建或删除文件/文件夹? Or which folder is recommended for this kind of file/folder operations?或者对于这种文件/文件夹操作,推荐使用哪个文件夹?
Using Windows 11, VS 2022 17.2.0 Preview 5.0 and.NET 6.0 without administrator privileges:在没有管理员权限的情况下使用Windows 11、VS 2022 17.2.0 Preview 5.0和.NET 6.0:
Your code worked fine for me.你的代码对我来说很好用。
Output: 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?检查目录的 ACL:是否允许您的帐户创建新文件?
(Right-click the directory -> Properties -> Security -> Select your own user and check your permissions.) (右击目录 -> 属性 -> 安全 -> Select 你自己的用户并检查你的权限。)
Usually you should not create files directly under your %localappdata%
directory.通常你不应该直接在你的
%localappdata%
目录下创建文件。
If you need a temp-file, I would recommend to use Path.GetTempFileName()
for getting a unique file name.如果您需要临时文件,我建议使用
Path.GetTempFileName()
来获取唯一的文件名。
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.如果您想将文件存储更长的时间,那么我建议您在
%localappdata%
中为您的应用程序创建一个目录并将文件保存在那里。
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: Output:
Creating directory: C:\Users\Edgar\AppData\Local\MyApplication
File created: C:\Users\Edgar\AppData\Local\MyApplication\myFile.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.