【问题标题】:How to access a text file in Windows Form Application如何在 Windows 窗体应用程序中访问文本文件
【发布时间】:2013-12-26 09:31:04
【问题描述】:

我已在 Windows 窗体应用程序中添加了一个文本文件并尝试访问此文件。

这是我的代码..

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());
            }
        }
    }

Licence.txt 在我的项目文件夹中,但每次 (fi.Exists) 都只是错误的,并且程序从流程中出来而不显示 Form1() 窗口.. 请帮我。 提前谢谢..

【问题讨论】:

  • 不应该是:Application.StartupPath+@"\Licence.txt"吗?将前斜杠更改为反斜杠
  • 正如 Ben 所说,另外:该文件在您的项目文件夹中,但它也在您的输出文件夹中(“复制到输出目录”)?
  • 这就是掌握调试的重要性。只需在fi.Exists 行上设置一个断点并检查 Fileinfo 路径。将其复制到 Windows 资源管理器中,然后查看该文件是否确实存在。很有可能,事实并非如此。

标签: c# io windows-forms-designer file-handling windows-applications


【解决方案1】:

string filePath = Path.GetFullPath("Licence.txt");

这个文件应该出现在安装文件夹中。这样你就可以得到文件路径。

【讨论】:

    【解决方案2】:

    [1] 问题是它在您的项目文件夹中的位置:) Application.StartupPath 进入调试模式

    你的项目\bin\调试

    你的文件在吗?

    尝试逐步调试并查看您获得的路径以及文件是否存在

    [2] 未显示您的窗口,因为您错过了添加

    Application.Run(new yourForm());

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      不做字符串连接使用Path.Combine()

      System.String s = Path.Combine(Application.StartupPath,"Licence.txt");
      

      【讨论】:

        【解决方案4】:

        使用这个:

        string s = Path.Combine(
          Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
          "Licence.txt");
        

        不要尝试手动组合路径,因为您必须处理路径分隔符...使用内置函数要好得多!

        最后记得在你的项目中的License.txt文件上设置Copy to Output属性。

        【讨论】:

          猜你喜欢
          • 2019-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-24
          • 2010-10-04
          • 2019-01-05
          • 2016-06-15
          相关资源
          最近更新 更多