Cannot find file Exception with FileStream, opens in Explorer - c#

I have the following code:
FileStream file = new FileStream(#"\\srv\dscan$\001\unknown\2012-04\0011200001001700_001.pdf", System.IO.FileMode.Open);
It always throws a FileNotFoundException. The strange thing is that if I paste the exact same path above into Windows Explorer, the file can be found and opened perfectly OK.
What can be causing this? Is there a special way of handling file streams on shared network drives?

What can be causing this?
The account under which is executing the process containing this code doesn't have sufficient permissions to read from this location.

What Darin Dimitrov says.
The user account that you are logged in under in Windows seems to have the sufficient permissions or maybe you have entered a username and password before which you marked as 'remember'.
When running your code it probably does under minimal rights (UAC) or maybe you are creating a Windows Service, which runs under a different account all together.
Problem could also be related to the dollar sign, which indicates that you are trying to reach a hidden share. I don't know if that is a problem in itself, but could have impact on your (in)sufficient rights.

C# treats a path differently from a windows explorer.
And one more thing, if you check those posts:
Reading File From Network Location
you will find that you need some more work on the configurations.

Related

.NET Directory.Move results in Access to path is denied with network paths

I know there are a bunch of these questions already but none of the ones I found depict the scenario I have.
So what I want to do is to
move a directory via Directory.Move. Both source and destination are on a file server in the same network so both paths are network paths (starting with \\SERVER rather than a drive letter).
The application that‘s supposed to do that gives me an „UnauthorizedException: Access is denied“. Because it‘s confidential I can‘t show the log or code.
But I tried to reproduce it by simply calling Directory.Move via PowerShell ([System.IO.Directory]::Move()). There I receive the same message. Access to path X is denied. Nothing more.
This error appears with any user context. An admin, an admin with „run as admin“, the user of the application and the user of the application with „run as admin“.
Manually moving these directories works without a problem.
Creating a directory with Directory.CreateDirectory works too. But moving the newly created Directory results in the same error.
Executing these commands on the file server works just fine if using the local path. Using the network path (still on the actual fileserver, though) results again in the Acces is denied error.
Could it be, that the issue lies within the path rather than the directory? The permissions are all correct and set (as said, manual operations work). Are there any workarounds?
I really don‘t know what to do. I‘m the only developer at this company and the rest are network engineers and can‘t help
me either.
There are a number of things that could be causing it to deny access and it would be hard to point you in the right direction without seeing your code. But here are 2 scenarios that might help you.
Scenario 1 - The filepath you are using is in the wrong format, Usually I have had a access denied because the format of the network filepath was actually wrong. I would recommend looking up examples of how you should pass the filepath. Also have a talk with your network engineers and ask them about the rights that have been setup for that filepath.
Scenario 2 - You might be passing a filepath when you also need to specify a name. Now I dont have all the details but I also had issues in the past using the Directory.Move function where I actually had to specify a filename to move it to. You do this by just adding the file and extension to the end of the target path to copy to.
If you could post some more information I might be able to point you in the right direction but this is what I can think of for now. I hope this works for you or atleast brings you closer to an answer. Good luck!
*Edit: It looks like I am wrong on the scenarios, Have a look at this link Can you move a file/folder across a network share in .NET?
You will have to first manually create the filepath and then copy all the files into the new filepath you have created. It seems like Directory.Move has problems when different machines are used.

What are security issues in creating file

I am writing log for my application at a path saying :-
"C:\Folder1\Folder2\Myfile.txt" (Configurable)
if this file does not exist I am creating folder structure and file inside my code(If there is no C drive I pop up a message saying log directory doesnt exist).
In code review a colleague said that I should not create folder and files using code rather should ask the client to create the file and only perform write operation on this file.
He says there are security issues with this but not sure what, so I thought of posting it here.
Please help me deciding whether I should create file if not exist or ask the client to create on every installation.
What are the security implications with the first approach?
The write issues are that the user trying to create in the C root folder, may not have permissions to create it there. Never assume the user is an admin always.
Also this is the problem with windows' UAC which will be a problem.
Yes there could be issues. Your program will most likely run under the interative user account and therefore be subject to any UAC conditions imposed on it.
One approach, if this is just a log file, would be to use a temporary file, so use:
http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx
This should be created in a an area local to the logged on user that should allow writing of files.
The security issue i see is the ability of your web application to access and write the files inside the directory (configurable, as you mentioned).
To verify the the access by checking the permissions given to the account under which your apppool is running
or through code see this
No code is inherently unsafe. This all depends on how rest of your code looks like, but as a general rule of thumb you should limit which files your application can access and how it can access them. Limit this as much as possible, without damaging your applications functionality.
Security vulnerabilities which may come from this is allowing user to read file which he shouldn't read, or write to an important file and damage it that way. For example, if file path is being created using user input, user may modify the path so that he accesses file which is not allowed to access.
If you create a path like so:
string filePath = "c:\\mysafefolder\\" + fileName;
and user enters a relative path, for example ..\Windows\Passwords.txt he will effectively gain access to c:\windows\passwords.txt.
If you configure your application to block access to any part of file system except mysafefolder, this attempt to read a secret file will fail.
This is just an example of what might happen, and why it is a good idea to limit your application permissions. Your code might be perfectly safe at this point, but limiting permissions is thinking ahead.

Access to the path denied error in C#

I have read a similar post, but i just cant figure out the problem.
I have changed the windows permissions and changed routes.
When i try to save a file it throws me the exception:
Access to the path **** denied.
string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
StreamWriter write = new StreamWriter(fs);
patient person = new patient();
patient.name = textBox1.Text;
patient.name2 = textBox2.Text;
You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. #"D:\test.txt") and the error will go away.
By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).
Did you try specifing some file name?
eg:
string route="D:\\somefilename.txt";
tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.
I have come across this error in my travels trying to read in an XML file.
I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.
File details:
The path and file name are valid, the file exists
Both the service account and the logged in user have Full Control permissions to the file and the full path
The file is marked as Read-Only
It is running on Windows Server 2008 R2
The path to the file was using local drive letters, not UNC path
When trying to read the file programmatically, the following behavior was observed while running the exact same code:
When running as the logged in user, the file is read with no error
When running as the service account, trying to read the file generates the Access Is Denied error with no details
In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
You do not have permissions to access the file.
Please be sure whether you can access the file in that drive.
string route= #"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create.
Please try this, now you can create.
TLDR : On my end, it had something to do with AVAST ! => Whitelist your application.
All of a sudden, I also got this UnauthorizedAccessException problem in the windows WPF program I'm writing. None of the solutions worked - except I couldn't figure out how to elevate my application to full privileges (not using VS) while at the same time, being already on the administrator account, I didn't feel the need to dig that deep in permission concerns.
The files are image files (jpg, psd, webp, etc.) I wasn't trying to open/write a directory, it has always been a valid path to a file, and I needed to write to the file, FileAccess.ReadWrite was inevitable. The files (and any of their parent directory) were not readonly (I even checked by code prior calling new FileStream(path, mode, access, share) via FileInfo.IsReadOnly) - so what happenned all of a sudden ???
Thinking about : I had an had drive crash, so I unpacked a backup of my solution code from another drive. In the meantime, I added codes in my application to PInvoke APIs to directly read hard drive sectors physical bytes as well as USB plug/unplug monitoring.
I started to get the Exception when I added those, but even though I temporarly removed the related codes from the application, I still got the UnauthorizedAccessException.
Then I remembered one thing I've done long ago, a painstaking similar issue where I wanted my application to communicate sensible data via Wifi, which was to add the executable among AVAST exceptions, and the assembly directory aswell (My app was already among the authorized apps through firewall)
Just did it for my application in AVAST settings, AND THE EXCEPTION IS GONE !!! Two whole days I'm lurking StackOverflow and the web to get moving on, FINALLY !
Details : I can't pinpoint exactly what AVAST didn't like in my application as the only changes I made :
Retrieved then launched the backup code - it worked like a charm, files (images) opens/write without problems (3 days ago)
Added USB detection (3 days ago - Just tested the code, didn't tried to open an image)
Added PInvoke physical drive direct read (2 days ago - FileStream, and the logic to define where/how to scan the damaged drive - Just tested the code, didn't tried to open an image)
Added image format detection starting from Jpg/Jfif.. 2 days ago, got the exception upon testing the code.
While searching for solutions, added an Image Gallery WPF UserControl to diplay pictures based on their signature and check which files gives the exception : almost all of them (some files opens/write okay - why ???)
Tried everything I've found on SO (since the last 2 days) until I opened AVAST settings and whitelist my application.
... now I can move on into adding a bunch of file signatures to retrieve as many datas as I could.
If this may help those who like me, aren't failing on the "I'm passing a directory path instead that of a file", yet, have no time to learn exactly why antiviruses think our own code is a malware.
Just Using the below worked for me on OSX.
var path = "TempForTest";

File system paths and Directory.Exists()

I'm at a bit of a loss on this one ... can't seem to understand what is going on.
I have an app that writes some files to a configured output directory, but before that, when the application loads I do this ...
string path = ConfigurationManager.AppSettings["TempDir"];
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
My problem is that in my case the path is a network based location "\MyServer\Share" and when i use that path it works, but the path i'm using is actually "Z:\" because the share is mapped and is automatically mapped in all user sessions across the network.
I want to use "Z:\" but it doesn't work throwing back an error saying "all or part of the path doesn't exist".
I immediately thought "oh this must be permissions" so i checked it against say "G:\" which worked and has the same permissions applied ...
For all shares in question my user account has full control permissions on the location.
Initially i thought it might be something like this: Directory.Exists not getting mapped directory
But then i remembered that it couldn't be that the app is running under another account because I checked and
its only a console app
the line before is this:
AppDomain.CurrentDomain.SetThreadPrincipal(new WindowsPrincipal(WindowsIdentity.GetCurrent()));
.. as i understand the purpose of this is to ensure that the appdomain is running under the context of the current windows user, that includes all "threads created within the app domain" unless otherwise specified
Any ideas?
EDIT:
Looking through process monitor as Richard suggests ( see comments below) shows that if i use the full unc path "\MyServer\Share" the request is made as I would expect, if i use the mapped path "Z:\" it still requests the full unc path "\MyServer\Share" (presumably it is doing some form of translation in the inner workings of .net).
so no matter what i'm requesting a full unc path "\MyServer\Share" and yet only by explicitly specifying the full unc path can i access it ... weird !!!
The code posted above is exactly as I have written it in my console application, there's no other stuff going on yet other than that principle thing as these are the first lines of code to execute in my console application.
Hmmm ...
EDIT 2:
Ok now i'm really confused, when put a breakpoint on the configuration file request line above and run it up to the breakpoint then clear out process monitor and step over that and the if statement nothing appears in the process monitor as I would expect it to ...
Why would that happen?
You can not use mapped drive as a path you need to make a shared directory and give it the permission you need (read or write) and then connect to it like this:
\ServerName\SharedDirectoryName\OneMoreDirectory
I seem to have found an odd bug in the debugging tools / .net framework ...
When the debugger is attached to my app it fails, when the debugger is not attached it works as expected.
The recommendation is always to use a full unc path but the calls to Directory.Exists(path) and Directory.Delete(path) resolve mapped drives before making the call as process monitor reveals so although it is recommended it is not required.
I have found however that running the app then attaching visual studio manually seems to allow the app to run as epected and allow the require debugging in my situation.
This solution comes with the "Works on my PC garantee" only ... i take no responsibility for anything said in this question :)
Thank you to everyone for the help however I seem to have resolved it ... UAc was good advice and so was process monitor ... thanks guys ... really helped :)

Intermittent "File in Use" Error

I have some code that I wrote to basically clear out the directory every time the program runs through this point. I didn't want to bother enumerating files. If this is a bad way to do this, please tell me.
My main question, however, is about how to deal with the following: one of the files in the folder appears to be in use when it is most certainly not. The program runs on a ButtonClick event, and it exploded the first four or five times, but it worked after I confirmed that nobody was using the file on the server. There is only one person besides myself that would have been using it, and he confirmed that there was nothing running on his side that would be touching the file. Any ideas for what would cause this error/how to avoid it/how to handle it?
I am also having trouble reproducing the error...
string directory = #"\\server\directory\folder\";
DirectoryInfo di = new DirectoryInfo(directory);
if (di.Exists)
di.Delete(true);
Directory.CreateDirectory(directory);
If you are using Windows XP, this may help : http://msdn.microsoft.com/en-us/library/dd997370.aspx#remove_open_handles
Just an extract from the top of this page :
"If you are running Windows XP or earlier, a delete operation on a file or directory that follows an enumeration could fail if there is an open handle that remains on one of the enumerated directories or files."
You may also use a software like Unlocker to identify the process locking your file.
If the file is in use, then someone is most certainly using it. :)
If you can access the server the files reside on, you can use a tool such as Process Explorer to find out which process has opened the file.

Categories