首页 > 解决方案 > .net 核心文件传输到网络位置

问题描述

我有将文件从一个位置传输到网络驱动器的代码。源位置可能是我的电脑或其他网络驱动器。我正在使用 .NET Core 2.1 和 C#。我的代码与 MSDN 示例中的代码类似。

问题是当目标是我 PC 上的文件夹时,这可以正常工作,但是当它是如下所示的网络位置时,文件不会移动到指定位置。源中的文件确实被删除了,并且没有任何错误。

我已确保我登录的 Windows 帐户对网络位置具有明确的权限。我假设这是我的应用程序正在运行的上下文。我也环顾四周并尝试进行模拟以显式使用具有权限的帐户并找到一些代码来执行此操作,但似乎这在 .net 核心中不起作用。

我错过了什么?我怎样才能让它工作?

string fileName = @"TestFile.txt";
string sourcePath = @"C:\users\myuser\docs";
string targetPath =  @"\\10.10.10.148\docs";

// 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.Move(sourceFile, destFile, true);

标签: c#asp.net-core

解决方案


将您的移动命令放在 try catch 块中以查看返回的实际错误(如果有)。

try
{
    // To copy a file to another location and 
    // overwrite the destination file if it already exists.
    System.IO.File.Move(sourceFile, destFile, true);
}
catch (Exception ex)
{
    //show error message using appropriate method for 
    //Console Application
    Console.WriteLine(ex.Message);
    //OR Web Application //
    Response.Write(ex.Message);
    //OR WinForms Application
    MessageBox.Show(ex.Message);
}

然后,您将获得更多信息来帮助进行故障排除。


推荐阅读