I am trying to copy a text file in an other text file line by line. It seems that there is a buffer of 1024 character. If there is less than 1024 character in my file, my function will not copie in the other file.
Also if there is more than 1024 character but less a factor of 1024, these exceeding characters will not be copied.
Ex:
2048 character in initial file – 2048 copied
988 character in initial file – 0 copied
1256 character in initial file – 1024 copied
private void button3_Click(object sender, EventArgs e)
{
// écrire code pour reprendre le nom du fichier sélectionné et
//ajouter un suffix "_poly.txt"
string ma_ligne;
const int RMV_CARCT = 9;
//délcaration des fichier
FileStream apt_file = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
textBox1.Text = textBox1.Text.Replace(".txt", "_mod.txt");
FileStream mdi_file = new FileStream(textBox1.Text, FileMode.OpenOrCreate,FileAccess.ReadWrite);
//lecture/ecriture des fichiers en question
StreamReader apt = new StreamReader(apt_file);
StreamWriter mdi_line = new StreamWriter(mdi_file, System.Text.Encoding.UTF8, 16);
while (apt.Peek() >= 0)
{
ma_ligne = apt.ReadLine();
//if (ma_ligne.StartsWith("GOTO"))
//{
// ma_ligne = ma_ligne.Remove(0, RMV_CARCT);
// ma_ligne = ma_ligne.Replace(" ","");
// ma_ligne = ma_ligne.Replace(",", " ");
mdi_line.WriteLine(ma_ligne);
//}
}
apt_file.Close();
mdi_file.Close();
}
Two issues:
FileStream,StreamWriter, andStreamReaderclasses should be insideusing { }blocks. They implementIDisposable, so you need to be callingDispose, and theusingblock will do that for you. If you do this, that’s actually all you have to fix (which I’ll explain in a minute). Doing this also means you no longer need to callClose().mdi_line.Flush()before closing it. This will cause the buffer to be written to the file immediately.Calling
Disposeon theStreamWriterclass autmatically callsFlush, which is why theusingblock will correct the problem.