Thursday, November 01, 2007

C# File Access Problem

 
 I faced the problem in C# file access that is as follows :
 
 
C# file accessing Sample :
-------------------------------------


// Specify file, instructions, and privelegdes
FileStream file = new FileStream("test.txt", FileMode.Open);

// Create a new stream to read from a file
StreamReader sr = new StreamReader(file);

// Read contents of file into a string
string s = sr.ReadToEnd();

// Close StreamReader
sr.Close();

// Close file
file.Close();

  Everywhere people used the sample like this...

I also followed this sample during the development.
 I read the char by char from the streamReader object.

test.txt file is less than 1024 bytes size then the problem will not arise.

But if  file size is greater than 1024 bytes, I got the problem.


 I read the char by char from the StreamReader object.

 char[] szChar;
 szChar = new char[1];
                   strmReader.Read(szChar,0,1);

  
 After reaching the 1024 th character, I got the first character from the file...

So the StreamReader doesnt Read characters from file after 1024 characters.


Reason :

 By default StreamReader buffer size is 1024 bytes. we can also allocate the StreamReader buffer size.

if we read characters after 1024th character, StreamReader's Read() fn will returns the first character from the stream.

This will be repeated...


To avoid this problem, I allocated the StreamReader's size as File Size.
Now  we can traverse from beginning of the file to the end of the file.The code is as follows :

 

 FileStream myFile = new FileStream("test.txt",FileMode.Open);
 FileInfo fileInfo  = new FileInfo("test.txt");
 int FileLength = (int)fileInfo.Length; 
 StreamReader strmReader = new StreamReader( myFile, System.Text.Encoding.UTF8,false, FileLength);

 

 

 

 

 

 

 


 

No comments: