C# 如何在Windows窗体应用程序中访问文本文件
我在Windows窗体应用程序中添加了一个文本文件,并尝试访问此文件 这是我的密码C# 如何在Windows窗体应用程序中访问文本文件,c#,io,windows-forms-designer,file-handling,windows-applications,C#,Io,Windows Forms Designer,File Handling,Windows Applications,我在Windows窗体应用程序中添加了一个文本文件,并尝试访问此文件 这是我的密码 static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); System.String s = Application.StartupPath+"/Licence.txt"; Syst
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.String s = Application.StartupPath+"/Licence.txt";
System.IO.FileInfo fi = new System.IO.FileInfo(s);
if (fi.Exists)
{
if (fi.Length == 0)
{
Application.Run(new Form1());
}
}
}
license.txt在我的项目文件夹中,但每次(fi.Exists)都是false,并且程序从流中出来时没有显示Form1()窗口。。
请帮帮我。
提前感谢。使用此:
string s = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Licence.txt");
不要尝试手动组合路径,因为您必须处理路径分隔符。。。使用内置函数更好
最后,请记住在项目中的License.txt文件上设置
Copy to Output
属性。无需使用字符串连接
[1] 问题是它在项目文件夹中的位置:)Application.StartupPath处于调试模式 您的项目\bin\Debug 你的档案在那里吗 尝试一步一步地调试,并查看您得到的路径以及文件是否存在 [2] 您的窗口未显示,因为您错过了添加 Application.Run(newyourform())
希望有帮助:)字符串filePath=Path.GetFullPath(“license.txt”)
此文件应显示在安装文件夹中。这样您就可以获得文件路径。它不应该是:
Application.StartupPath+@“\license.txt”
?如Ben所说,将正斜杠改为反斜杠,另外:文件在项目文件夹中,但也在输出文件夹中(“复制到输出目录”)?这就是为什么掌握调试非常重要的原因。只需在fi.Exists
行上设置一个断点,并检查Fileinfo路径。将其复制到windows资源管理器中,查看文件是否确实存在。很可能不是。
System.String s = Path.Combine(Application.StartupPath,"Licence.txt");