Miguel
Miguel

Reputation: 79

Writing to a text file with a variable for the name

Alright, so my question is; I'm trying to save a file to the C: drive in a folder. Now, I know how to do this for regular files like

using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");

What I've been trying to figure out is how I can make it so that the name of text file is the replaced with a variable so Its more like

using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");

Is there anyway I can do this?

I apologize for my poor question asking skills.

Upvotes: 3

Views: 9541

Answers (2)

Michael Petrotta
Michael Petrotta

Reputation: 60902

The StreamWriter constructor, like many other constructors and method calls, takes a string argument. You can pass it any string you like. In your first code sample, you're passing the constructor a "string literal" - an unnamed string variable with a constant value. Instead, you can pass a standard string variable, that you construct beforehand. For instance:

string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));

I usually like to use the Path.Combine static method when I concatenate path components. Helps me avoid problems with missing or doubled backslashes:

string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");

And, finally, with the string verbatim modifier, you avoid those ugly double-backslashes, that are otherwise necessary because the backslash is the "escape" character in non-verbatim strings:

string path = System.IO.Path.Combine(@"c:\Folder", name + ".txt");

Here's the Microsoft developer reference page for strings in C#. Worth a read, as is the larger C# language reference.

Upvotes: 4

Thomas
Thomas

Reputation: 64645

var inputPath = "c:\\Folder\\TextFile.txt";
var folderPath = Path.GetDirectoryName( inputPath );
using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )

Upvotes: 0

Related Questions