File system paths and Directory.Exists() - c#

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 :)

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.

Looking to launch a local exe on a remote machine without having the resurces on the remote machine

So I have built some code, it's quite simple basically it stops all active input from keyboard and mouse until a text file of a certain name appears in the C:\Temp directory. It also has a manifest file to run it as administrator on start up.
So I found something that on the surface looks like it fulfils my needs of being able to do this task however upon running it I found out that the project has been compiled in x86 and does not run on my x64 machine. Here is the reference to the project if anyone would like to look into it, it's a very smartly designed piece of code that does an interesting objective. It also explains clearly enough what I am trying to accomplish.
So after implementing this (and failing) I have setup a couple other avenues to try, one is VBA through excel with the VBA copying itself to and from the machines in a list and running itself, then there is using VBS to write the entire code as a txt file on the target machine change the extension and then execute it remotely. I have just started researching these but I imagine the problems of running as an administrator amongst other things will crop up again to be dealt with. To be honest though I would really prefer to do this in C# only as that is the language I'm trying to go further in so I'm interested in this challenge. If anybody knows of a similar library of code or application I could look into to achieve what I'm trying I would appreciate being pointed in the right direction.
I would try and be more specific about what libraires/API's im trying to implement but the truth is I don't know what libraries I need to even interact with to get what I want. My goal is to have C# executable code on my machine and a tool that can run that executable on another machine.
Thanks
Thanks to the help in comments from #Nick.McDermaid I was able to correctly open and build the project I was trying to download. Unsure what caused the issue previously with me not being able to open and interact with the code but now I have it I shall pursue this avenue further to accomplish my goal.
As an addendum one other avenue I tried for executing code remotely was through VBS where I used
set svcproc=getobject("winmgmts:{impersonationLevel=impersonate}!\\"&MachineName & "\root\cimv2:win32_process")
scmd="""C:\Program Files\Internet Explorer\iexplore.exe"" -framemerging ""https://gifyu.com/images/Boo-Ghost-Gif.gif"""
'scmd="C:\Windows\notepad.exe"
iret=svcproc.create(scmd,null,null,pid)
set svcproc=nothing
to execute something that existed on the remote machine but I ran into a LOT of security policy issues where I could launch the process but I couldn't bring it to the foreground as the Malware tracker on the machine thought it was an attack and quashed it immediately.

Cannot find file Exception with FileStream, opens in Explorer

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.

What directory (if any) should I use to store settings file for my add-in?

I've developed an add-in and now I'd like to enable it to store/retrieve settings upon the launch of Outlook. I've checked the current working directory using Environment.CurrentDirectory but when I tried to File.WriteAllText to it, I failed due to access rights. So, my question is twofold.
Will any directory suffice or is there a recommended one?
Do I need to store the settings in a local file or is there a neater method?
I use the Environment class as follows.
String dir = Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData);
A bit lengthy syntax but it does the job well. Not sure if you'll have full access rights from an add-in, though. Also, It'd be good to know if somebody will suggest a better storage method. Once I used a web service until I discovered that my user often will do his job while sitting on the train (read: off-line). It worked unless he didn't reboot his machine before getting on board.

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