Accessing a network file share with C#
Asked Answered
P

2

12

I've never done this before, and all of the research I've done indicates needing user names/passwords. Here's the situation: I am developing an app for my company, and the app needs to access a file share on the network. Let's call that file share \\server\TPK. My app needs to get files from this folder on this share. Is working with file shares on a company network the same as working with File I/O (System.IO)? Can anyone give me any guidance on how to do this? I know this probably is an elementary question, and I apologize for that.

Passkey answered 14/8, 2013 at 19:46 Comment(1)
#3701371Piers
C
17

Generally speaking, yes. It's the same. Just use the UNC path as you've stated. You may have security issues depending on how your application is running but a quick test should be something like:

FileInfo myFile = new FileInfo(@"\\server\TPK\some-file-that-exists.pdf");
bool exists = myFile.Exists;

Just point it to a file that you know exists and see if it finds it. You may have to deal with Credentials or Identity depending on the configuration of your application. If this is the case you should get an Exception stating "Access Denied" or something along those lines.

Communion answered 14/8, 2013 at 19:53 Comment(3)
In my case the Exists property for FileInfo is true, but when I try to create a File object for the same path, I get an AccessDenied exception!Lovelace
Ok, it worked for me now. I was assuming while opening the file that FileAccess would be Read, if not specified, but when I explicitly specified it, I could access the file for reading.Lovelace
For some reason when using File.Exists("Some path...") it failed and I was pulling my hair out as I had used that to test the fileshare successfully in the past. Your approach however has worked in its stead, interesting.Gwenn
P
1

It's not that obviously possible.

I had to do something like this:

public class SharedLocationConnector : IDisposable
{
    char driveLetter;
    bool disposed = false;

    public char ConnectToLocation(string path, string userName, string pwd)
    {
        driveLetter = MapShare(path, userName, pwd);
        Thread.Sleep(2000); //It takes that much for connection to happen
        return driveLetter;
    }

    private char MapShare(string path, string username, string pwd)
    {
        char driveLetter = GetAvailableDriveLetter();
        string cmdString = "net use " + driveLetter + ": " + path + ((username != string.Empty) ? " /user:" + username + " " + pwd : "");
        ManagementClass processClass = new ManagementClass("Win32_Process");
        object[] methodArgs = { cmdString, null, null, 0 };
        object result = processClass.InvokeMethod("Create", methodArgs);
        return driveLetter;
    }

    public void  Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!disposed)
        {
            //Dispose managed objects. Thre are none.

            //Dispose unmanaged objects
            if (!String.IsNullOrWhiteSpace(driveLetter.ToString()))
                FileUtils.DisconnectSambaShare(driveLetter);
            disposed = true;
        }
    }

    ~SharedLocationConnector()
    {
        Dispose(false);
    }

    public void Disconnect()
    {
        if (!String.IsNullOrWhiteSpace(driveLetter.ToString()))
            DisconnectShare(driveLetter);
    }

    private void DisconnectShare(char driveLetter)
    {
        string cmdString = "net use " + driveLetter + ": /DELETE";
        ManagementClass processClass = new ManagementClass("Win32_Process");
        object[] methodArgs = { cmdString, null, null, 0 };
        object result = processClass.InvokeMethod("Create", methodArgs);
    }

}
Perryperryman answered 14/8, 2013 at 20:55 Comment(4)
I didn't have to do anything near this complex... I just simply used normal System.IO to access the share, as the other answer suggests... I wonder why you had to implement something this complex?Passkey
Doesn't that require pre-connection to UNC path before code executes?Perryperryman
I'm not sure what you mean by preconnection... if the service account that the app is using to access the share has permissions to do so, then I would imagine it wouldn't be an issue.Passkey
True. But mine was the case where service account did not have access to share. User id and pwd had to be passed from application's configuration.Perryperryman

© 2022 - 2024 — McMap. All rights reserved.