1

I am creating multiple files using StreamWriter, I want these files to be created in a specific directory

StreamWriter w = new StreamWriter(File.Create(name + ".txt"));
w.WriteLine(name);
w.Close();

here name is variable that is used as file name and also to be written in that file, but my problem is I want this file to be created in specific directory.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76

5 Answers5

4

Use Path.Combine

Path.Combine uses the Path.PathSeparator and it checks whether the first path has already a separator at the end so it will not duplicate the separators. Additionally, it checks whether the path elements to combine have invalid chars.

Quoted from this SO post

Also it would be fruitful to check if you name variable contains invalid characters for a filename.

You may first remove invalid characters from name variable using Path.GetInvalidFileNameChars method :

var invalidChars = Path.GetInvalidFileNameChars();
string invalidCharsRemoved = new string(name
  .Where(x => !invalidChars.Contains(x))
  .ToArray());

Quoted from this SO post

string directory = "c:\\temp";

Instead of

File.Create(name + ".txt")

Use

string filename = invalidCharsRemoved + ".txt"
File.Create(Path.Combine(directory , filename ))
Ankit
  • 5,733
  • 2
  • 22
  • 23
3

You can include the path too:

string path = "C:\\SomeFolder\\";
File.Create( path + name + ".txt");

Or Use Path.Combine like:

File.Create( Path.Combine(path, name + ".txt") );
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • i have tried this but got error "path format is not correct" – Adnan Haider Aug 24 '17 at 10:44
  • string ww = (@"U:\scripts\"); StreamWriter w = new StreamWriter(File.Create(ww+name + ".txt")); w.WriteLine(name); w.Close(); – Adnan Haider Aug 24 '17 at 10:47
  • 1
    why not use Path.Combine ? – Ankit Aug 24 '17 at 10:50
  • would you please elaborate path.combine – Adnan Haider Aug 24 '17 at 10:50
  • see my answer and link posted above – Ankit Aug 24 '17 at 10:51
  • @AdnanHaider please post the content of `name` – Mong Zhu Aug 24 '17 at 10:53
  • @AdnanHaider how can you get a "path format is not correct" exception? does `name` hold the entire path to the file? or is it a simple filename string like `"filename"` ?? – Mong Zhu Aug 24 '17 at 11:11
  • @MongZhu `name` contains some thing like (U:\TDScripts\acchf122_0023 – Adnan Haider Aug 24 '17 at 11:23
  • and due to thisU:\TDScripts\ the files are created on this path not he path specified .how can i remove TDScipts from `name` – Adnan Haider Aug 24 '17 at 11:38
  • @AdnanHaider I posted a way how to get rid of the old path and inject your own into it. Have a look at my answer – Mong Zhu Aug 24 '17 at 12:09
  • @AdnanHaider glad to hear. is `!!` a sign of happy excitedness of angryness ?=! :) – Mong Zhu Aug 24 '17 at 12:16
  • @AdnanHaider If you like to can mark the answer that helped you as accepted. This will help future visitors to see that a thread is closed and has a definite answer. If you don't know how to do it [this post](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) might help. Have a nice day – Mong Zhu Aug 24 '17 at 12:18
  • @MongZhu i have already marked everyone's answer as everyone gave a valuable answer like ankit sharma – Adnan Haider Aug 24 '17 at 12:33
  • @AdnanHaider that is not what I mean. You have upvoted every answer, but you can only accept 1 answer! choose one and click the check mark below the score of the answer, like described in the post. it will turn green afterwards :) – Mong Zhu Aug 24 '17 at 12:50
2
        FileStream fileStream = null;
        StreamWriter writer = null;
        try
        {

           string folderPath = @"D:\SpecificDirecory\";
           string path =  Path.Combine(folderPath , "fileName.txt");

           if (!Directory.Exists(folderPath))
           {
               Directory.CreateDirectory(folderPath);
           }

           fileStream = new FileStream(@path, FileMode.Create);
           writer = new StreamWriter(fileStream);
           writer.Write(fileBuilder.ToString());            
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            writer.Close();
            fileStream.Close();
        }
Unni Krishnan
  • 94
  • 3
  • 9
2

name contains some thing like @"U:\TDScripts\acchf122_0023"

ok according to the new information from your comment you need actually to get rid of the old path and directory.

You can use the Path.GetFileNameWithoutExtension method to achieve that. After that you can use Path.Combine to create your own path.

Here is an example to demonstrate this:

string myDirectory  = @"C:\temp";

string oldPathWithName = @"U:\TDScripts\acchf122_0023";

string onlyFileName = Path.GetFileNameWithoutExtension(oldPathWithName);

string myNewPath = Path.Combine(myDirectory, onlyFileName + ".txt");

Console.WriteLine(myNewPath);

I hope this solves your problem.

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
1

You can declare a path for your directory like this :

string path = @"c:\folder\....";

Then with the following command:

File.Create( path + name + ".txt");

You will get what you want

dim mik
  • 939
  • 1
  • 10
  • 30