I sometimes get false negatives when I check if a directory on a network path exists.
When I check if the folder exists the method returns 'true' most of the time. Sometimes it switches to 'false' and reports 'false' for every call for about 5 seconds.I think it changes to 'false' when someone who hasn't accessed the network drive for a while (maybe 15 minutes) accesses it for the first time. The network drive is not offline during these 5 seconds. I'm still able to navigate it in Windows Explorer. Therefore I am not sure that this really causes the false negatives.
Even the Directory.CreateDirectory() method fails sometimes with an error stating the directory already exists. But the docs say it only tries to create the directory if it does not already exist.
It doesn't matter whether I use
new DirectoryInfo("PATH").Exists;
Directory.Exists("PATH");
Upon request in the comments I also tried
var di = new DirectoryInfo("PATH");
di.Refresh();
di.Exists;
And which format for the path I use
N:\MyFolder (N: is the same previousely mapped network drive)
\\192.168.1.10\MyShare\MyFolder
I saved the credentials to this server in Windows Credentials Manager.
Does anyone have any idea what could cause this inconsistency?
Related
I am using Directory.Exists() in my windows service (that is programmed in C#, 3.5 framework)to check to see whether a particular directory exists in the drive. When I run in local machine it works fine, meaning I am able to access the directory.
But when I deploy the windows service on a Virtual Machine, and start the service, it is not able to find the directory even though the directory exists. The directory is mapped on as
Q: drive, Q:\\temp\\local\\ folder
But the windows services always returns false for the Directory.Exists().
However when I give C:\ drive in place of Q:\ it works, but does not work for a mapped drive. I have tried with the UNC path, and I have made sure the mapped drive have the administrative rights and infact the read, write and execute permission. But it still returns false.
Can anyone please tell me why? And how to resolve?
Make sure the drive is mapped under the same user as the Service is running. If you map the drive as user A, it is not automatically mapped for anyone else too.
Mapped drives are only restored during interactive login which services generally do not perform:
Map a network drive to be used by a service
Short version: You can't do it, use the full UNC path instead.
This is most probably a problem with privileges. Your Windows service is probably running under an account which doesn´t have enough privileges to access the network path.
This is a possible duplicate: Accessing mapped folder from a Windows Service written in C#
Another possible solution is to use impersonation, check it out:
http://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.90).aspx
UPDATE
Came to think of it;
Try changing the identity of the application pool to a user with the same rights as your user.
As #Sriram pointed out the Directory.Exists() method will fail if any error occurs. What sort of exception do you get if you try to access the path?
Eg (for both mapped and UNC in case there is something going on there):
DirectoryInfo diMapped = new DirectoryInfo(#"Q:\temp\local\folder");
DirectoryInfo diUNC = new DirectoryInfo(#"\\servername\fnsw\tmp\126");
Note: Assuming that the white space before 'folder' in your path is a typo?
Steps to troubleshoot
Try accessing the network path manually in "Run" [WindowKey + R]
Try to access your map drive i.e.: M:\
Make sure you are the account owner of the mapping (mapping should be done under your account)
Go to Property and see if "Run As Administrator" is unchecked.
Remove mapping and re-add the mapping.
Make sure available offline (or sync offline) is turned off and folder is available from another computer.
Hope this helps!
I have some networkshares mounted to my PC. I can see them in the Windows Explorer, with drive letters etc. If I try to read or write with c#, I always get a DirectoryNotFoundException.
The method to check if the directory exists
Directory.Exists(#"N:\test")
returns false (N:\ is the mounted share). If I open the path in the Explorer, the path exists.
Can you imagine, what the problem could be?
Thank you!
I just tested to see if this works when I run the application as administrator and it failed. So the reason is most probably because the user under which you execute the code doesn't have access to the path.
As you confirmed that you were indeed running the application with elevated privileges, you should follow the indications that are also suggested in this answer :https://stackoverflow.com/a/11268410/674700:
(...) open an administrative command prompt - where you have an
elevated token all the time - and create a matching drive mapping from
there (net use h: \server\share1). Since the standard user and the
elevated administrator have a common understanding of what "H:" drive
means, everything runs okay.
Well, I just try to assume why you can get this exception, here it is;
First of all, Directory.Exists() method works fine for network mounted drives. There could be a few more reason that why you get DirectoryNotFoundException in your work.
From MSDN;
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.
I believe you have one of this but since we can't acces your computer, we can't know the real reason :)
I have made a little app that's running on a Win7-PC. All it does, is to check the content of a network drive at 1:00 O'clock in the morning (and compare it to a folder on its local hard drive), and if there´s differences, copy the differences to this folder.
The problem is, sometimes it can not find the network drive.
When the app starts up, the network drive is found using a button on the app which starts OpenFileDialog, and the resulting drive letter is put into a textbox beside the button. From that point it should just run by itself. The PC is never turned off.
When it says the network drive can not be found, I can manually press the button on the very same app, select the drive in the OpenFileDialog (the drive letter never changes), and the app will run flawless in a couple of days. Then the problem occurs again.
The question is: Why can the network drive be accessed through the OpenFileDialog on my app, but my app can not?
My app start the copy-process using this function (called with "Y:\") to determine whether the drive is present or not:
public bool fn_drive_exists(string par_string)
{
DirectoryInfo di_dir = new DirectoryInfo(par_string);
if (di_dir.Exists)
{
return true;
}
return false;
}
...and sometimes it returns a False, until I "wake it up" using the OpenFileDialog.
What does OpenFileDialog do, that my app do not?
According to this SO post, the problem should be gone if you use UNC path instead of mapped network drive.
If your destination has a static ip address, I suggest you use that ip address instead of domain name for network drive
This SO post describes a similar scenario to what you've described.
One of the links posted as a response to that question led me to this MSDN article which provides a variety of reasons as to why one might encounter errors when trying to access shared network drives by using a mapped drive letter.
Microsoft's suggestion (see below) is to simply use a UNC path.
A service (or any process running in a different security context) that must access a remote resource should use the Universal Naming Convention (UNC) name to access the resource.
To answer your actual question more specifically, with regards to why it suddenly can't access the network share, I would venture a guess to say that the network share is being disconnected by Windows due to an idle timeout, as discussed in KB297684. Any attempt to access the disconnected drive will be met with a small wait as the connection to the network share is re-established, which could presumably be what is causing your issue.
To test this theory, try writing some data to a file on the network drive at a relatively short interval (every 10 minutes, perhaps?) to try and convince Windows that the drive is still active.
You can also try to use:
System.IO.Directory.Exists(par_string);
instead of writing Your own method for the same thing. I would expect a framework method to be able to "wake" the network drive.
Note: Method also works for UNC paths (something like \\<server name or IP address>\<shared folder>)
Like Harvey says, use the UNC path to access the folder, for instance \\server\sharedfolder. In place of \\server use the name of the server. Your computer has a name and so does the server. You can also use the IP address if you know it. You replace \sharedfolder with the path to the files. Some examples:
\\AppsServer\c$\Program Files(x86)
\\FileServer1\d$\Users\John\My Documents
The c$ represents that the C drive is the shared folder. If the entire drive is not shared, you will need to share the specific folder. You can do that by logging onto the server, right clicking the folder, and selecting Properties. Then you go to the Sharing tab and check the Share this folder checkbox. If your shared folder is called MyShare, then your UNC path to access the folder will be
\\server\MyShare
I have a C# application which loads at startup, and logs data to a network drive, which is mounted as X:
When the machine first boots, the application throws an error that X:\ is not available. If I restart the app, same error.
However, if I open Windows Explorer and double click to browse the drive, I can then run the application and it will connect to X: just fine.
Do network drives not automatically initialise on startup, despite being mapped? Is there a way to set them to initialise automatically?
Ive had the exact same issue. I don't know if there are better methods out there, but I added this to my code before accessing the mapped drive.
Process mapDrive = new Process();
mapDrive.StartInfo.FileName = "net.exe";
mapDrive.StartInfo.Arguments = #"use c: \\server\share";
mapDrive.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
mapDrive.Start();
That way whether the drive is available at start up or not it will always be available.
See How Can I Access a Mapped Network Drive here on SO for a list of things to check. My guess is either the drive does not exist for your user, or there is a permissions issue accessing it. Another item to check is the order in which you call Impersonate, assuming that you are doing so, that is.
According to Cannot Access Files On Mapped Drive From Windows Service you should not do this at all. See the Microsoft link(s) provided in the accepted answer.
I've written a Windows Service in C#/VS2008/.NET3.5 that monitors some FTP directories with FileSystemWatchers and moves the files out to another location for processing. I noticed today that it throws errors stating "The parameter is incorrect" soon after the service has started up, but if we wait a few minutes the file gets copied without incident. I saw that the error message is often related to incorrect permissions, but I verified permissions on the directories (target and source) were correct and as I said the file move works just a few minutes later.
Here's a snippet of the code that gets called when the file is finished copying into the FTP directory being monitored:
//found the correct source path
string targetDir = dir.TargetDirectory;
string fileName = Path.GetFileName(e.FullPath);
errorlocation = "move file";
string targetFilePath = Path.Combine(targetDir, fileName);
if (File.Exists(targetFilePath))
{
File.Delete(targetFilePath);
}
File.Move(e.FullPath, Path.Combine(targetDir, fileName));
dir refers to and object with information about the directory the file was being loaded into. e is the FileSystemEventArgs. Targetdir is grabbed from the directory's settings in a custom configuration block in the app.config that tells the service where to copy the new files to.
I didn't include the code here, but I know it's failing on the File.Move (last line above) due to some EventLog entries I made to trace the steps.
Any idea as to why the move fails soon after the service startup, but works fine later?
Basic overview of the process in case it sheds some light: external vendors FTP us a number of files each day. When the file comes in, my code identifies who the file is coming from based off the FTP directory and then loads settings to pass on to SSIS jobs that will parse and save the files. There are maybe a dozen or so directories being monitored right now each of which has its own configuration setting for the SSIS job. Is it possible that the system gets confused as startup and just need some time to populate all the settings? Each source directory does have its own FileSystemWatcher on it.
Thanks for your help.
The first question I'd answer is, what are the values of these when it fails:
e.FullPath
targetDir
fileName
chances are one of those values isn't what you expect
I'm marking this answered because the problem went away. We haven't changed anything in the code, but it now works immediately after restart. The best theory we have is: since I posted this, the client I was working for moved offices and as part of the migration a lot of system and network policies were updated and server setting tweaked for the new environment. It's likely one (or more) of those changes fixed this issue.
Further support for this theory: prior to the move my development VM could not run web browsers. (I'd click to load the browser and it wouldn't work, sometimes it would appear briefly in Task Manager and then disappear.) After the office move, this problem no longer occurs.
So it was likely some network setting somewhere that caused issues. Sorry I can't be more specific.