user5404530
user5404530

Reputation: 27

creating a file using a variable name in current directory in c#

Suppose I have string variable string id='sample'. I want to make a file named sample.txt in my current directory (Environment.CurrentDirectory) using the string variable and after that I want to get the full path of the text file. How will I do that? Normally we can create a text file(say: sample.txt) in current directory in this way:

    string path=Directory.GetCurrentDirectory();
    string FileName = path + "\\sample.txt";
    File.Create(FileName);

But how will I do this using the string variable and after creation how will I get the full path of the sample.txt file?

Upvotes: 1

Views: 7210

Answers (2)

Ethan Ollins
Ethan Ollins

Reputation: 108

I think this may help:

string path = Environment.CurrentDirectory() + "\\" + id + ".txt";

Upvotes: 0

Steve
Steve

Reputation: 216353

Use the Path.Combine method

string path=Directory.GetCurrentDirectory();
string FileName = Path.Combine(path, id + ".txt";
File.Create(FileName);

and at this point you have already the full path name in the FileName variable but you can use other methods of the Path class

string fullPathName = Path.GetFullPath(FileName);

Upvotes: 1

Related Questions