简体   繁体   中英

How to read and write to a Windows “Network Location”

In Windows you can add a FTP site as a named Network Location using the "Add Network Location Wizard". For instance, a user can add a location called "MyFtp".

In .Net, how can I access (list, read and write) files in that location? Does Windows abstract away the implementation (WebDAV, FTP or else) and make it look like a local folder to my .Net program? If that's the case, how do I specify the path parameter in File.WriteAllText(path, content) ? If not, how can I access the files?

No, Windows only handles that in Explorer. (They might have removed this in newer versions of Windows.) You will have to use some built in classes or implement FTP, WebDav and any other protocol yourself.

The MyFtp shortcut in the Network Locations is a shortcut to the FTP Folders shell namespace extension. If you want to use it, you would have to bind to the shortcut target (via the shell namespace) and then navigate via methods like IShellFolder::BindToObject or IShellItem::BindToHandler. This is very advanced stuff and I don't think there is anything built into C# to make it easier. Here are some references to get you started.

You can try this to read/write the content of a file at the network location

//to read a file
string fileContent  = System.IO.File.ReadAllText(@"\\MyNetworkPath\ABC\\testfile1.txt");
//and to write a file
string content = "123456";
System.IO.File.WriteAllText(@"\\MyNetworkPath\ABC\\testfile1.txt",content);

But you need to provide read/write permissions for network path to the principal on which the application is running.

you can use the FtpWebRequest -Class

here is some sample-code (from MSDN):

public static bool DisplayFileFromServer(Uri serverUri)
{
    // The serverUri parameter should start with the ftp:// scheme.
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    WebClient request = new WebClient();

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
    try 
    {
        byte [] newFileData = request.DownloadData (serverUri.ToString());
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        Console.WriteLine(fileString);
    }
    catch (WebException e)
    {
        Console.WriteLine(e.ToString());
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM