我之前遇到过一些问题,这些问题导致我的程序在所有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)) { } } }I have had some problems earlier which caused my program to crash in all Windows OS because I did not create a new file/directory for my file. Then I have assured that I have created file/folder before initializing ect. Now my program works in Windows XP but it doesn't work in Windows 7. By saying that it works I mean that it creates a file/folder needed for my program. By not working I mean that the file/folder isn't created in windows 7.
Could this code be the cause of the crash under Windows 7? If so, how could I fix it?
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%文件夹。
看看这里看到各种特殊文件夹。 您可能需要使用System.Environment.SpecialFolder.ApplicationData或System.Environment.SpecialFolder.CommonApplicationData 。 这将允许您在不需要提升权限的情况下写入数据。
The program files directory in Windows 7 can only be written to with elevated privileges. Are you running your code as an administrator? It's also bad practice to write to the program files folder. You should be using the %appdata% folder.
Take a look here to see the various special folders. You will likely want to use either System.Environment.SpecialFolder.ApplicationData or System.Environment.SpecialFolder.CommonApplicationData. This will allow you to write data without needing elevated privileges.
更多推荐
发布评论