Reputation: 235
This method I call from a backgroundworker dowork event
void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
try
{
files = root.GetFiles("*.cs");
int Vara = File.ReadAllText(files[0].Name).Contains("namespace") ? 1 : 0;
}
catch (UnauthorizedAccessException e)
{
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
}
The problem is that i'm getting exception on the line:
int Vara = File.ReadAllText(files[0].Name).Contains("namespace") ? 1 : 0;
Could not find file 'D:\C-Sharp\Search_Text_In_Files\Search_Text_In_Files\Search_Text_In_Files\bin\Debug\Logger.cs'
Upvotes: 3
Views: 1168
Reputation: 151730
Using FileInfo.Name
you're only getting the filename, not the full path.
Hence you're trying to read the file relative to the current directory, where it doesn't exist.
Obtain the full path instead, i.e. FileInfo.FullName
instead of FileInfo.Name
.
If you want to read all files, you should loop over the files instead of only reading the first (files[0]
), the latter of which is dangerous anyway, because that will throw if there are no files found.
foreach (var fileInfo in files)
{
int Vara = File.ReadAllText(fileInfo.FullName).Contains("namespace") ? 1 : 0;
}
Upvotes: 3
Reputation: 6234
You should replace Name
to FullName
of FileInfo
object:
void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
try
{
FileInfo[] files = root.GetFiles("*.cs");
foreach(FileInfo fileInfo in files)
{
int Vara = File.ReadAllText(fileInfo.FullName).Contains("namespace") ? 1 : 0;
// do something with Vara
}
}
catch (UnauthorizedAccessException e)
{
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
}
Reference FileInfo.FullName Property
Upvotes: 2