2011-01-11 12 views
4

を書く読んで、あなたはそのようなストリーム開く:のFileStream引数/ C++で

int variable = 45; 

ifstream iFile = new ifstream("nameoffile"); // Declare + Open the Stream 
     // iFile.open("nameofIle"); 

iFile >> variable; 

iFile.close 

を私はC#FileStreamを理解しようとしています。読み書きメソッドには配列とオフセットとカウントが必要です。この配列はどれくらいの大きさですか?私はちょうどそれに任意のサイズを与えるとそれはそれを埋めるでしょうか?その場合、Filestreamでファイルを読むにはどうすればいいですか? 私はどのくらいの配列を渡すのか分かりますか?

答えて

7

あなたは単に読み書きするStreamReaderStreamWriterラッパーを使用することができます。

using(StreamReader sr = new StreamReader(fileName)) 
{ 
    var value = sr.ReadLine(); // and other methods for reading 
} 



using (StreamWriter sw = new StreamWriter(fileName)) // or new StreamWriter(fileName,true); for appending available file 
{ 
    sw.WriteLine("test"); // and other methods for writing 
} 

または次のように実行します。fs.Lengthが長いこと

StreamWriter sw = new StreamWriter(fileName); 
sw.WriteLine("test"); 
sw.Close(); 
2
using (FileStream fs = new FileStream("Filename", FileMode.Open)) 
     { 
      byte[] buff = new byte[fs.Length]; 
      fs.Read(buff, 0, (int)fs.Length);     
     } 

注意してますのでint.MaxValueのようにチェックする必要があります< fs.Length。

そうでなければ、あなたがたFileStreamはそれを埋めるませんが、代わりに例外がスローされますところで、whileループの古い方法(fs.Readはバイト読みの実際の数を返す)

を使用しています。

1

.Readメソッドを呼び出すときに、結果のバイトが格納される配列を指定する必要があります。したがって、この配列の長さは少なくとも(Index + Size)にする必要があります。 書き込み中は、同じ問題が発生します。ただし、これらのバイトは配列から取得され、内部には格納されません。

1

FileStreamのreadメソッドの引数のバイト配列は、読み込み後にストリームからバイトを取得するため、長さはストリームの長さに等しくなければなりません。 MSDNから:

using (FileStream fsSource = new FileStream(pathSource, 
      FileMode.Open, FileAccess.Read)) 
     { 

      // Read the source file into a byte array. 
      byte[] bytes = new byte[fsSource.Length]; 
      int numBytesToRead = (int)fsSource.Length; 
      int numBytesRead = 0; 
      while (numBytesToRead > 0) 
      { 
       // Read may return anything from 0 to numBytesToRead. 
       int n = fsSource.Read(bytes, numBytesRead, numBytesToRead); 

       // Break when the end of the file is reached. 
       if (n == 0) 
        break; 

       numBytesRead += n; 
       numBytesToRead -= n; 
      } 
      numBytesToRead = bytes.Length; 

      // Write the byte array to the other FileStream. 
      using (FileStream fsNew = new FileStream(pathNew, 
       FileMode.Create, FileAccess.Write)) 
      { 
       fsNew.Write(bytes, 0, numBytesToRead); 
      } 
     } 

のStreamReaderは、ストリームからテキストを読み取るために使用される