Search code examples
c#pathstreamwriter

Change former path to custom path keeping the filename and create a file using stream writer in c#


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.


Solution

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