Check if folder is in use in C# - c#

Consider a network folder:
\\desiis\c$\Company\B2b\Monitor
On that machine, any process that tries to delete the directory Monitor receives an error because a user on the LAN has that directory open (likely with Windows Explorer).
Can I detect, via C# and .NET framework, if any user (and which user) has a particular directory open/in use?

I'm not sure if you can obtain the particular user in the directory but the DirectoryInfo class in C# .NET would probably be the best way to go.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo_members.aspx
Review the API at this link and you'll notice there is a method to get the information about WHEN the directory was last accessed but not by who. Also you can catch any exception when trying to delete a directory as it being unavailable (an exception will be thrown as you are probably well aware).
Also note that exception catching is costly and you should evaluate any slowdowns in your process by doing this.

No, there is no possibility I know.
It seems you'll have to catch the occuring Exception as a workaround.

Related

c# window application system.data.oledb.oledbexception operation must use an updateable query

I have made a window application that works very well when i ran through but after creating its setup it is throwing below mentioned exception. I have try to give full access to the database file but still it is not working.
system.data.oledb.oledbexception operation must use an updateable.
query
i am using window 7 and installation folder is c:\program files\abc\ and access db is in same folder. Is this any issue of permissions? Please assist me to remove this exception.
There can be some permission issue just refer this Link
http://www.mikesdotnetting.com/Article/74/Solving-the-Operation-Must-Use-An-Updateable-Query-error
Make sure the ASPNET account (or whatever account is in use at the time) has
Change permissions to the directory where the .mdb file is located. Access
needs to write some temp and locking files during the operation.

C# - Access to mounted networkdrive

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

Windows service can't write to %LOCALAPPDATA%

I have built an app that works only when not run as a Windows service. Well, the service runs, but it doesn't do what it should. The service uses the Local Service account. So to kick off debugging, I thought I'd start with something simple: have it create a directory when it starts:
Directory.CreateDirectory(
Environment.SpecialFolder.LocalApplicationData + "\\MyService");
When I started the service, it stopped almost immediately and Windows reported that fact. When I commented out the above statement, recompiled and re-installed, the service ran without stopping.
Obviously the above line throws an exception of some sort. I have no way of logging the error because I can't write to the file system. Any ideas why Local Service can't create a directory in its own %LOCALAPPDATA%?
You should use GetFolderPath with LocalApplicationData like so:
string folderName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"MyService");
Directory.CreateDirectory(folderName)
I think this might be because there is no special folder. When running as the local service account you are running under that user, not the logged in user. so you are requesting a special folder that probably wont exist, as I don't think the local service has a profile. (I may be wrong) - I was wrong :p
Just in case anyone pops by:
C:\Windows\ServiceProfiles\LocalService
is the local service profile folder, so it will end up in there.
If you want to debug it surround that line with a try catch, and then write the error to a file:
try
{
Directory.CreateDirectory(Environment.SpecialFolder.LocalApplicationData + "\\MyService");
}
catch (Exception ex)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\MyServicelog.txt",true);
file.WriteLine(ex.Message);
file.Close();
}
At least then you can see whats causing the error
Martyn
I suggest you write the exception details to the event log. All user accounts have permission to write to the event log as long as the log and source names have already been created by an administrator (which you can do simply by running the app as yourself first).
As to the root cause of the error, it may be because LocalService doesn't normally get a full set of profile folders created by default. I'm not sure whether this is by design, or simply what I have observed on various machines.

How to access File over the Network

I am having a hard time on this one, I have a folder over the network with public access (no credential restriction). I am trying to do a File.Exist or Directory.Exist and I keep on having a exception.
Can someone tell me the good way to do IO over the network.
EDIT 1 FOR DETAILS:
if i do execture => \agoodip\Public\test.txt I get the file etc etc
In my code it look like a basic
Directory.Exist(#"\\agoodip\Public") or
File.exist(#"\\agoodip\Public\test.txt")
The exception I get is Path not found.
EDIT 2 :
I am using Silverlight 3, Is there any security pattern to be aware of to lookup file on the network?
Thanks!
I don't believe that is going to work for you. Silverlight doesn't allow arbitrary access to the file system or shares. Silverlight runs within a sandbox environment so you have restricted access to the file system.
You need to begin your UNC path with two backslashes ("\\") if it refers to a network path rather than a local path.

How can my C# app test whether the user has "Read" access to a network share?

I work on a thick-client app that often runs into "issues" accessing network shares. Before doing any IO with the server, my app tests whether the share (usually of the form \\server\share$) exists. This works fine for detecting those scenarios in which the client has lost its connection to the server, but there are still those odd scenarios where the hidden share exists but the user does not have the rights to read from the within the share. Can someone share (no pun intended) the C# code required to test whether the current user can read files on a share? Should I be querying the share's ACL or the files within the share? What if the share is empty? What if the user is a local non-admin in a mixed environment (XP Pro workstation, Windows 2003 server without a domain on a Novell network)?
The easiest way is to just do it (i.e. try to read a file, for example). As Jared mentioned, there is no way to make sure that you will be able to read in the future (network failure, change of permissions, etc).
As far as code goes, you could use the DirectoryInfo class for some attempts at an answer:
string remotePath = #"\\server\share$";
bool haveAccess = false;
DirectoryInfo di = new DirectoryInfo(remotePath);
if (di.Exists)
{
try
{
// you could also call GetDirectories or GetFiles
// to test them individually
// this will throw an exception if you don't have
// rights to the directory, though
var acl = di.GetAccessControl();
haveAccess = true;
}
catch (UnauthorizedAccessException uae)
{
if (uae.Message.Contains("read-only"))
{
// seems like it is just read-only
haveAccess = true;
}
// no access, sorry
// do something else...
}
}
There are many shortcomings in the above code (such as the hard-coded "read-only" test), but it is just an example used to illustrate what you could do. DirectoryInfo has a few other helper methods that you can use to list the files in the folder. If you don't have access, the methods will throw an UnauthorizedAccessException exception which you can use to test why the access failed. Check out the info on GetAccessControl for further details on the exceptions it throws.
The #1 most reliable way to determine if you used to have permission to read from the share is to
Try and read from the share
Handle errors that could occur while reading and consider that a failed attempt
Unfortunately though based on your description you are trying to determine if you will have read permission to the share. There is no way to reliably determine this.
No matter how many ACLs, directories, etc ... you look at the moment you're done looking at them you could lose access to the share via any number of mechanisms. The most obvious one is the network share going down. All you can determine is that you used to have permission to the share.

Categories

Resources