Connecting Tech Pros Worldwide Forums | Help | Site Map

Could not load the file exception when trying to read a file with StreamReader

Newbie
 
Join Date: Oct 2007
Posts: 21
#1: Jul 8 '09
Hi,

I am using the following code to read a file.

DirectoryInfo dir = new DirectoryInfo(@"C:\");
try
{
if (dir.Exists)
{
FileInfo[] csvfiles = dir.GetFiles("*.csv");
foreach (FileInfo file in csvfiles)
{
Console.WriteLine(file.Name );
Console.Read();
using (StreamReader sr = new StreamReader(file.Name))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.

while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);

}
}
}

}
catch (Exception e)
{
Console.WriteLine(e.Message);
}


But, this code is running up to streamreader class and giving error saying that could not load file "C:\DotnetApplication\FileOperations\test.csv" - this is the file path where my application exists. The 'test.csv' file actually presented under C:\ directory.
Please advice how to fix this?

TIA

Member
 
Join Date: May 2009
Location: Goregaon, मुंबई IN :)
Posts: 85
#2: Jul 9 '09

re: Could not load the file exception when trying to read a file with StreamReader


When initializing the StreamReader object, you need to pass the full path in the constructor...

Expand|Select|Wrap|Line Numbers
  1. using (StreamReader sr = new StreamReader(dir.FullName+file.Name))
  2.  
Reply

Tags
c# ; streamreader;