My C# application throws a System.IO.IOExcepton (The directory name is invalid) for the following code for implementing a filewatcher:
public void OnChanged(object source, FileSystemEventArgs e)
{
开发者_如何学编程 DirectoryInfo dList = new DirectoryInfo(e.FullPath);
FileInfo[] TxtFiles = dList.GetFiles("*.TXT");
}
e.FullPath
is "C:/Documents and Settings/Bi/Application Data/TestApp/Reports\\0MA01P62240_000005798__TRI__4947712701738551.TXT".
If you notice it seems to append a "\\" to the path when it tracks the file. Any idea what the problem may be?
The path C:/Documents and Settings/Bi/Application Data/TestApp/Reports\\0MA01P62240_000005798_TRI_4947712701738551.TXT
isn't a directory name, it's a file name. That's why it says the directory name is invalid.
Use Path.GetDirectoryName to get the actual directory, as in:
string directoryName = Path.GetDirectoryName(e.FullPath);
It's also very strange that the FileSystemWatcher
is giving you a path with forward slashes; I can't argue with what you're seeing, but those really should be backslashes. You might want to check the Path
property of the FileSystemWatcher
to see if that path is hard-coded.
Does this give the same problem?
FileInfo fi = new FileInfo(e.FullPath);
DirectoryInfo di = fi.Directory;
FileInfo[] TxtFiles = di.GetFiles("*.TXT");
It's quite weird that the event arg e has a wrong value. Of course you can replace "\" with "/", however that's not the best way. I think you'd better tell us how you trigger the event.You know it's almost impossible that C# gives a wrong event argument unless you pass the value yourself.
精彩评论