将文本文件写入子文件夹

时间:2012-11-12 10:42:28

标签: c# winforms filepath streamwriter

我正在尝试将文本文件写入:C:\Test folder\output\,但不会将C:\放入。

这就是我目前的工作,目前有效,但开头有C:\

StreamWriter sw = new StreamWriter(@"C:\Test folder\output\test.txt");

我真的想把文件写到输出文件夹,但不必在前面有C:\

我尝试过以下操作,但我的程序只是挂起(不写出文件):

(@"\\Test folder\output\test.txt");

(@".\Test folder\output\test.txt");

("//Test folder//output//test.txt");

("./Test folder//output//test.txt");

无论如何我能做到这一点吗?

感谢。

4 个答案:

答案 0 :(得分:2)

据我所知,您希望将数据写入指定的文件夹。第一种方法是在代码中或通过配置指定文件夹。

如果您需要写入特定驱动器或当前驱动器,您可以执行以下操作

string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + @"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);

如果目录需要相对于当前应用程序目录,则用户AppDomain.CurrentDomain.BaseDirectory获取当前目录并使用../组合导航到所需的文件夹。

答案 1 :(得分:2)

一种常见的技术是使目录相对于exe的运行时目录,例如子目录,如下所示:

string exeRuntimeDirectory = 
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().Location);

string subDirectory = 
    System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
    // Output directory does not exist, so create it.
    System.IO.Directory.CreateDirectory(subDirectory);
}

这意味着安装exe的地方,它将创建一个“输出”子目录,然后可以将文件写入。

它还具有将exe及其输出文件保存在一个位置的优点,而不是遍布整个地方。

答案 2 :(得分:2)

您可以使用System.IO.Path.GetDirectoryName获取正在运行的应用程序的目录,然后您可以添加其余的路径..

我不明白你想从这个问题得到什么,希望这能得到它......

答案 3 :(得分:2)

感谢帮助人们。

我的一位同事也参与并帮助过,但@Kami也帮了很多。

我现在正在工作:

string path = string.Concat(Environment.CurrentDirectory, @"\Output\test.txt");

正如他所说:“CurrentDirectory是运行程序的地方。