Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream Not Writable in C# [duplicate]

Tags:

c#

I am using below code to read from source file and write to destination files.Below are the conditions: 1. I want that each file should contain only 3 or less that 3(for records in last file). 2. As soon as count reached 3, I want to create new file and start writing there. 3.Continue this process until reading finishes from source file. This code is throwing exception that "Stream was not writable."

 static void Main(string[] args)
    {
        int RecCnt = 10;
        int fileCount = RecCnt / 3;
        String SourceFile = @"D:\sample\test.txt";
        using (StreamReader sr = new StreamReader(SourceFile))
        {                
            while (!sr.EndOfStream)
            {
                String dataLine = sr.ReadLine();
                for (int x = 0; x <= (fileCount + 1); x++)
                {
                    String Filename = @"D:\sample\Destination_" + x + ".txt";
                    FileStream fs = new FileStream(Filename, FileMode.OpenOrCreate);
                    for (int y = 0; y <= 3; y++)
                    {
                        using (StreamWriter Writer = new StreamWriter(fs))
                        { 
                            Writer.WriteLine(dataLine);
                        }
                        dataLine = sr.ReadLine();
                    }
                    dataLine = sr.ReadLine();
                }
            } 
        }
    }

Please suggest.Let me know if you have better alternate approach as well.

like image 976
Mandar Avatar asked Oct 20 '22 11:10

Mandar


1 Answers

I am not sure this problem is there in code or not but if you want to create file with write acess than you can try

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

you can do this

//path of file and there is no need of creating filestream now
using (StreamWriter w = File.AppendText(path))
{
  for (int y = 0; y <= 3; y++)
  {
    Writer.WriteLine(dataLine);  
    dataLine = sr.ReadLine();  
  }
  w.Close();
}
like image 162
Pranay Rana Avatar answered Nov 04 '22 01:11

Pranay Rana