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

C# 将文件写入任何计算机上的项目文件夹,c#,file-io,io,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.Stream

我正在为一个班级做一个项目。我要做的是将解析后的指令导出到文件中。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”

是的,只需使用相对路径。如果您使用
@“\test.txt”
(顺便说一句,@只是说我在使用字符串文字,它不再需要转义字符,因此您也可以使用
“\\test.txt”
,它将写入相同的位置)它会将文件写入当前工作目录,在大多数情况下,该目录是包含程序的文件夹。

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

以下是示例代码:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
显示如何获取您将具有写入权限的用户配置文件文件夹。或者,您可以使用用户的
My Documents
文件夹来保存文件,同样,您也可以保证访问该文件夹。您可以通过调用

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

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

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

没有发生。此名为path的字符串正在存储值-“C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\ASP.NET临时文件\\vs\\ffd833a7\\9d30e44e”。不知道为什么。