尝试将文件从我的计算机复制到另一台计算机在同一网络
问题描述:
这里的是我的代码:尝试将文件从我的计算机复制到另一台计算机在同一网络
private void button1_Click(object sender, EventArgs e)
{
try
{
File.Copy(@"C:\Documents and Settings\subhayan\Desktop\QBpluginlink.txt", @"\\10.10.10.148\C:\QBpluginlink.txt", true);
}
catch (Exception ex)
{
}
}
当该代码被执行我得到的异常
给定的路径的格式不支持
任何人都可以告诉我我可能在哪里弄错了吗?
答
问题是您要将文件复制到的UNC路径中的C:
。要么你改变这是在目标计算机上的有效共享,或者你使用的管理共享(如果这些被启用,该帐户拥有足够的权限来这样做):
@"\\10.10.10.48\ValidShareName\QBpluginlink.txt", // Valid share name
@"\\10.10.10.48\C$\QBpluginlink.txt", // Administrative share
答
这条道路不会即使工作你在Windows资源管理器中尝试过。如果您有权限尝试一个适当的文件共享的UNC路径:
\\10.10.10.148\c$\QBpluginlink.txt
注意c$
,它是由Windows中的默认管理共享设置访问C:
驱动器 - 但您需要正确的权限。或者根据Markus的回答创建一个特定的分享。
答
目的地必须是一个有效的文件路径,在你的情况下一个有效的UNC路径。
“\ 10.10.10.48 \ C:\ QBpluginlink.txt”无效,因为您引用的是该计算机的c:驱动器,您需要在目标服务器中创建一个共享文件夹并使用该路径。
或者使用默认驱动器共享:例如, \ 10.10.10.48 \ C $ \ QBpluginlink.txt
答
从MSDN:
string fileName = @"QBpluginlink.txt";
string sourcePath = @"C:\Documents and Settings\subhayan\Desktop";
string targetPath = @"\\10.10.10.148\C$";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
请确保您有访问复制文件去服务器
你打我给它+1 – CSL
@Markus 有没有办法提供用户名和密码的路径? – Mainak
如果您模拟此帐户,还可以在特定帐户下运行代码。但在这种情况下,您有责任以安全的方式存储凭据。如果您可以先在Windows资源管理器中使用它,则会更容易,例如通过授予应用程序帐户的访问权限或指定凭据并将其保存在Windows密码存储区中。如果基本访问已到位,您的应用程序不需要做任何特殊的事情。 – Markus