I am trying to write a function to determine if a file exists. The two methods prove to return inconsistent results (fileExists() seems to provide accurate results, compared to isFileFound(), that returns false positives - i would have expected an exception when trying to create the instance).
protected bool isFileFound(string path, string fileName) { System.IO.FileInfo fi = null; bool found = false; try { fi = new System.IO.FileInfo(path + fileName); found = true; } catch (Exception e) { baselogger.Fatal(e.Message + " " + e.StackTrace + " \n" + path + fileName); } return found; } protected bool fileExists(string path, string pattern) { bool success = false; try { success = File.Exists(path + pattern); } catch (Exception e) { baselogger.Warn(e.Message + " " + e.StackTrace + " " + e.Source); } return success; }
Neither seems to be able to resolve a UNC path of the following syntax: \\abcserver\c$\xyzfolder\foo.bar
Any idea why the unc path is failing for these methods would be greatly appreciated.
The File. Exists() method returns true if the file exists and false when the file doesn't exist or the caller does not have read access to the file. If you want to check the presence of a directory instead, use the Directory. Exists() method.
The isDir() function is used to check a given file is a directory or not.
If the file doesn't exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).
Check to make sure the file was successfully opened by checking to see if the variable == NULL. If it does, an error has occured. Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop.
You can create a FileInfo for an non-existing file. But then you can check the FileInfo.Exists property to determine whether the file exists, e.g:
FileInfo fi = new FileInfo(somePath); bool exists = fi.Exists;
Update: In a short test this also worked for UNC paths, e.g. like this:
FileInfo fi = new FileInfo(@"\\server\share\file.txt"); bool exists = fi.Exists;
Are you sure that the account (under which your application is running) has access to the share. I think that (by default) administrative rights are required to access the share "c$".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With