Write a text file to a sub-folder

萝らか妹 提交于 2019-12-24 07:03:26

问题


I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.

i.e.

This is what I have at the moment, which currently works, but has the C:\ in the beginning.

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

I really want to write the file to the output folder, but with out having to have C:\ in the front.

I have tried the following, but my program just hangs (doesn't write the file out):

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

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

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

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

Is there anyway I could do this?

Thanks.


回答1:


I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.

If you need to write to specific drive or current drive you can do the following

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

If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.




回答2:


You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..

I don't get clearly what you want from this question , hope this get it..




回答3:


A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:

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

This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.

It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.




回答4:


Thanks for helping guys.

A colleague of mine chipped in and helped as well, but @Kami helped a lot too.

It is now working when I have:

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

As he said: "The CurrentDirectory is where the program is run from.



来源:https://stackoverflow.com/questions/13342263/write-a-text-file-to-a-sub-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!