Determining If File Exists Using C# and Resolving Unc Path

Determining if file exists using c# and resolving UNC path

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$".

How to (quickly) check if UNC Path is available

How's this for a quick and dirty way to check - run the windows net use command and parse the output for the line with the network path of interest (e.g. \\vault2) and OK. Here's an example of the output:

C:\>net use
New connections will be remembered.

Status Local Remote Network

-------------------------------------------------------------------------------
OK O: \\smarty\Data Microsoft Windows Network
Disconnected P: \\dummy\Data Microsoft Windows Network
OK \\vault2\vault2 Microsoft Windows Network
The command completed successfully.

It's not a very .netish solution, but it's very fast, and sometimes that matters more :-).

And here's the code to do it (and LINQPad tells me that it only takes 150ms, so that's nice)

void Main()
{
bool available = QuickBestGuessAboutAccessibilityOfNetworkPath(@"\\vault2\vault2\dir1\dir2");
Console.WriteLine(available);
}

public static bool QuickBestGuessAboutAccessibilityOfNetworkPath(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string pathRoot = Path.GetPathRoot(path);
if (string.IsNullOrEmpty(pathRoot)) return false;
ProcessStartInfo pinfo = new ProcessStartInfo("net", "use");
pinfo.CreateNoWindow = true;
pinfo.RedirectStandardOutput = true;
pinfo.UseShellExecute = false;
string output;
using (Process p = Process.Start(pinfo)) {
output = p.StandardOutput.ReadToEnd();
}
foreach (string line in output.Split('\n'))
{
if (line.Contains(pathRoot) && line.Contains("OK"))
{
return true; // shareIsProbablyConnected
}
}
return false;
}

Or you could probably go the route of using WMI, as alluded to in this answer to How to ensure network drives are connected for an application?

file Exists c# visual studio 2017

the service windows in the configuration I have Account LocalSystem I must change it ?

Yes, you must change this. The LocalSystem account won't have any permissions for the computer at 10.125.16.22. This is true even if it's the same computer! The UNC path will force a network access, and LocalSystem won't present any credentials over the network. Therefore File.Exists() will always return false, no matter the actual state of the file. This is covered at the end of the Remarks section of the documentation.

The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Additionally, it's almost always poor practice to use File.Exists() in the first place. Instead, just try to copy the file and handle the exception if it fails. You need to do this anyway, because there are lots of reasons a file copy might fail that have nothing to do with the file existing. This is also faster, because as slow as exception handling can be it's still usually much faster than the extra set of disk/network I/O operations invoked by the File.Exists() check.

Speed up File.Exists for non existing network shares

Use Threads to do the checks. I think that threads can be timed out.

Check if directory exists on Network Drive

If UAC is turned on, mapped network drives only exist "by default" in the session they are mapped: Normal or elevated. If you map a network drive from explorer, then run VS as admin, the drive will not be there.

You need to enable what MS calls "linked connections":
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System: EnableLinkedConnections (REG_DWORD) = 0x1

Background Information about "two logon sessions" with UAC: http://support.microsoft.com/kb/937624/en-us

How to resolve unc paths via a C# Process Class?

Turns out it was a simple case of spaces in UNC paths - = |

The c# code was sound. It turns out that if your accessing a network resource via UNC path via an application, i.e a c# command line application, internal or not, and your UNC path is passed in as a parameter. It should be wrapped in double quotes if it has spaces in the path.

Otherwise without double quotes, your path passed in as a parameter or a hard coded value somewhere, must NOT HAVE ANY SPACES WITHIN IT! OTherwise it will not work.

Directory.Exists not working for a network path

When you run the code in Visual Studio it runs under the the rights of your user.

When you run the code in IIS it runs in the identity of the Application Pool which by default is the built in user "Network Service" this is a local user account which does not have access outside the local machine.

The rights on the network share are the first layer, after that the NTFS rights on the directory are checked.

You need to change the identity of the application pool to a domain user with the same rights as your user.



Related Topics



Leave a reply



Submit