[英]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.