在Windows 7下创建新文件和目录时,我的代码是否会导致崩溃?(Could my code cause a crash when creating a new file and directory

编程入门 行业动态 更新时间:2024-10-25 04:23:48
在Windows 7下创建新文件和目录时,我的代码是否会导致崩溃?(Could my code cause a crash when creating a new file and directory under Windows 7?)

我之前遇到过一些问题,这些问题导致我的程序在所有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.

更多推荐

本文发布于:2023-04-29 12:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是否会   新文件   代码   目录   Windows

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!