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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With