【问题标题】:Write file to project folder on any computer将文件写入任何计算机上的项目文件夹
【发布时间】:2013-10-12 02:03:34
【问题描述】:

我正在为一个班级做一个项目。我要做的就是将解析后的指令导出到文件中。微软有这个例子解释了如何写入文件:

// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";

// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);

file.Close();

我对那部分很好,但是有没有办法将文件写入当前项目的环境/位置?我想这样做而不是硬编码特定路径(即"C:\\test.txt")。

【问题讨论】:

    标签: c# file-io io


    【解决方案1】:

    是的,只需使用相对路径。如果你使用@".\test.txt"(顺便说一句@只是说我正在做一个字符串文字,它消除了对转义字符的需要,所以你也可以做".\\test.txt"它会写入同一个地方)它将写入文件到当前工作目录,在大多数情况下是包含您的程序的文件夹。

    【讨论】:

      【解决方案2】:

      您可以使用Assembly.GetExecutingAssembly().Location 获取主程序集 (.exe) 的路径。请注意,如果该路径位于受保护的文件夹内(例如 Program Files),除非用户是管理员,否则您将无法在那里写入 - 不要依赖此。

      这里是示例代码:

      string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
      string fileName = Path.Combine(path, "test.txt");
      

      This question / answer 展示了如何获取您将拥有写入权限的用户配置文件文件夹。或者,您可以使用用户的My Documents 文件夹来保存文件 - 再次保证您可以访问它。您可以通过调用获得该路径

      Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
      

      【讨论】:

        【解决方案3】:

        如果您想获取程序的当前文件夹位置,请使用以下代码:

        string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
        string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
        

        将数据写入文件的完整代码:

        string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
        string fileName = Path.Combine(path, "test.txt");
        
        if (!File.Exists(fileName))
        {
            // Create the file.
            using (FileStream fs = File.Create(fileName))
            {
                Byte[] info =
                    new UTF8Encoding(true).GetBytes("This is some text in the file.");
        
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }
        

        【讨论】:

        • 没有发生。这个名为路径的字符串正在存储值 - “C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\Temporary ASP.NET Files\\vs\\ffd833a7\\9d30e44e”。不知道为什么。
        猜你喜欢
        • 1970-01-01
        • 2012-12-06
        • 2020-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多