我之前遇到过一些问题导致我的程序在所有 Windows 操作系统中崩溃,因为我没有为我的文件创建新文件/目录。然后我确信在初始化 ect 之前我已经创建了文件/文件夹。现在我的程序可以在 Windows XP 中运行,但不能在 Windows 7 中运行。我说它可以运行是指它创建了我的程序所需的文件/文件夹。不工作是指文件/文件夹不是在 Windows 7 中创建的。
此代码可能是 Windows 7 下崩溃的原因吗?如果是这样,我该如何解决?
private static string dir = Environment.GetFolderPath
(Environment.SpecialFolder.ProgramFiles) + @"\folder\";
private static string file = dir + @"\Settings.txt";
private string text;
public void CheckFileStatus()
{
if (!Directory.Exists(dir))
{
DirectoryInfo directory = Directory.CreateDirectory(dir);
}
if (!File.Exists(file))
{
using (FileStream fileStream = File.Create(file))
{
}
}
}
最佳答案
Windows 7 中的程序文件目录只能以提升的权限写入。您是否以管理员身份运行代码?写入程序文件文件夹也是不好的做法。您应该使用 %appdata% 文件夹。
看看here查看各种特殊文件夹。您可能希望使用 System.Environment.SpecialFolder.ApplicationData
或 System.Environment.SpecialFolder.CommonApplicationData
。这将使您无需提升权限即可写入数据。
关于c# - 在 Windows 7 下创建新文件和目录时,我的代码会导致崩溃吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8860629/