簡體   English   中英

如何讀寫Windows的“網絡位置”

[英]How to read and write to a Windows “Network Location”

在Windows中,可以使用“添加網絡位置向導”將FTP站點添加為命名的網絡位置。 例如,用戶可以添加一個名為“ MyFtp”的位置。

在.Net中,我如何訪問(列出,讀取和寫入)該位置的文件? Windows是否將實現(WebDAV,FTP或其他)抽象化,並使其看起來像.Net程序的本地文件夾? 如果是這樣,如何在File.WriteAllText(path, content)指定path參數? 如果沒有,如何訪問文件?

不,Windows僅在資源管理器中處理。 (他們可能已在Windows的較新版本 中將其 刪除。) 您將必須使用一些內置類或自己實現FTP,WebDav和任何其他協議。

網絡位置中的MyFtp快捷方式是FTP文件夾外殼名稱空間擴展的快捷方式。 如果要使用它,則必須綁定到快捷方式目標(通過外殼名稱空間),然后通過IShellFolder :: BindToObject或IShellItem :: BindToHandler之類的方法進行導航。 這是非常高級的東西,我認為C#內置沒有任何東西可以使其變得更容易。 以下是一些入門指南。

您可以嘗試使用此方法在網絡位置讀取/寫入文件的內容

//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);

但是,您需要為運行應用程序的主體的網絡路徑提供讀/寫權限。

您可以使用FtpWebRequest -Class

這是一些示例代碼(來自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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM