Reputation: 944
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.
Upvotes: 1
Views: 15014
Reputation: 944
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.
Upvotes: 3
Reputation: 9639
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.
Upvotes: 2
Reputation: 5223
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..
Upvotes: 2
Reputation: 19407
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.
Upvotes: 2