将文件写入任何计算机上的项目文件夹

时间:2013-10-12 02:03:34

标签: c# file-io io

我正在为一个班级的项目工作。我要做的是将解析的指令导出到文件。 Microsoft有这个例子,它解释了如何写入文件:

// 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")。

3 个答案:

答案 0 :(得分:18)

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

答案 1 :(得分:8)

您可以使用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)

答案 2 :(得分:0)

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

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