• C# 控制台 访问拷贝远程共享文件到服务运行本地


    一:控制台版本.net 5.0

    二:结果如下图:

    三:上代码:

                1:入口代码:

    public class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine("开始执行文件拷贝!");
    DiskHandle diskHandle = new(@"\\192.168.0.52\ReclaimerScannerDataShare","administrator", "Dell123456");
    diskHandle.DownLoad( @"E:\\ReclaimerScannerDataShare", out string errorInfo);
    Console.Read();
    }
    }

             2:下载拷贝代码:

    public class DiskHandle
    {
    public string userName;
    public string passWord;
    public string FullPath;

    public DiskHandle(string FullPath, string strUserName, string strPwd)
    {
    this.FullPath = FullPath;
    this.userName = strUserName;
    this.passWord = strPwd;
    }

    /// <summary>
    /// 共享路径下载文件
    /// </summary>
    /// <param name="strFullPath">远程文件全路径</param>
    /// <param name="strTargetFile">保存到本地的文件路径</param>
    /// <param name="errorInfo">错误信息</param>
    /// <returns></returns>
    public bool DownLoad(string strTargetFile, out string errorInfo)
    {
    errorInfo = string.Empty;
    try
    {
    //string strRemotePath = Path.GetDirectoryName(strFullPath);
    //if (!File.Exists(strFullPath))
    //{
    // return false;
    //}
    int status = NetworkConnection.Connect(this.FullPath, this.userName, this.passWord); //连接远程共享文件夹
    if (status != 0)
    {
    errorInfo = this.FullPath + "," + NetworkConnection.GetErrorString(status);
    return false;
    }
    else
    {
    if (!Directory.Exists(strTargetFile))
    {
    Directory.CreateDirectory(strTargetFile);//文件夹存在同名文件,直接创建同名文件
    }
    CopyDirectiory(this.FullPath, strTargetFile);
    return true;
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    //throw ex;
    return false;
    }
    }

    public static void CopyDirToNDir(string srcpaht, string destpath)
    {
    if (Directory.Exists(srcpaht) && Directory.Exists(destpath))
    {
    CopyDirectiory(srcpaht, destpath);
    }
    }

    /// <summary>
    /// 读取指定流文件到指定文件
    /// </summary>
    /// <param name="strFullPath">具体源文件路径包含后缀名文件</param>
    /// <param name="strTargetFile">具体目标文件路径包含后缀名文件</param>
    public static void ReadlyFile(string strFullPath, string strTargetFile)
    {
    using (FileStream fileStream = new FileStream(strFullPath, FileMode.Open))
    {
    //读取
    int readCount;
    int bufferSize = 2048;
    byte[] buffer = new byte[bufferSize];
    readCount = fileStream.Read(buffer, 0, buffer.Length);
    FileStream outputStream = new FileStream(strTargetFile, FileMode.Create);
    while (readCount > 0)
    {
    outputStream.Write(buffer, 0, readCount);
    readCount = fileStream.Read(buffer, 0, bufferSize);
    }
    outputStream.Close();
    }
    }

    /// <summary>
    /// 同步源文件到目标文件路径下
    /// </summary>
    /// <param name="strFullPath">完全路径</param>
    /// <param name="strTargetFile">目标完全路径</param>
    public static void CopyDirectiory(string strFullPath, string strTargetFile)
    {
    try
    {
    int num = 0;
    Console.WriteLine($"拷贝文件执行中……;");

    DirectoryInfo directory = new(strFullPath);
    FileSystemInfo[] fileSystemInfos = directory.GetFileSystemInfos(); //获取目录想文件和子目录 当前一级目录
    foreach (FileSystemInfo item in fileSystemInfos)
    {
    var dirname = $"{strTargetFile}\\{item.Name}";
    if (item is DirectoryInfo) // 是否为文件夹
    {
    if (!Directory.Exists(dirname))
    {
    Directory.CreateDirectory(dirname);
    }
    CopyDirToNDir(item.FullName, dirname); // 递归复制子文件夹
    }
    else
    {
    DirectoryInfo desdirectory = new(strTargetFile);
    FileInfo[] desfileInfos = desdirectory.GetFiles(item.Name);
    if (desfileInfos == null || desfileInfos.Length == 0)
    {
    File.Copy(item.FullName, dirname, true); // 复制文件
    num += 1;
    }
    }
    }
    Console.WriteLine($"拷贝文件完成数量:{num}个;");
    }
    catch (Exception e)
    {

    }
    }
    }

            3:辅助 连接共享网络 代码:

    public class NetworkConnection
    {
    //创建网络连接
    [DllImport("mpr.dll")]
    public static extern int WNetAddConnection2A(NETRESOURCE[] lpNetResource, string lpPassword, string lpUserName, int dwFlags);

    //取消现有网络连接
    [DllImport("mpr.dll")]
    public static extern int WNetCancelConnection2A(string sharename, int dwFlags, int fForce);

    /// <summary>
    /// 连接远程共享文件夹
    /// </summary>
    /// <param name="remotePath">文件夹路径</param>
    /// <param name="username"></param>
    /// <param name="password"></param>
    /// <returns></returns>
    public static int Connect(string remotePath, string username, string password)
    {
    //必须是\\127.0.1.1\test格式,最后不能带斜杠
    if (remotePath.EndsWith("\\"))
    {
    remotePath = remotePath.Substring(0, remotePath.Length - 1);
    }
    NETRESOURCE[] share_driver = new NETRESOURCE[1];
    share_driver[0].dwScope = RESOURCE_SCOPE.RESOURCE_GLOBALNET;
    share_driver[0].dwType = RESOURCE_TYPE.RESOURCETYPE_DISK;
    share_driver[0].dwDisplayType = RESOURCE_DISPLAYTYPE.RESOURCEDISPLAYTYPE_SHARE;
    share_driver[0].dwUsage = RESOURCE_USAGE.RESOURCEUSAGE_CONNECTABLE;
    share_driver[0].lpRemoteName = remotePath;
    //连接前先断开一次,否则会报错
    Disconnect(remotePath);
    int ret = WNetAddConnection2A(share_driver, password, username, 1);
    return ret;
    }

    /// <summary>
    /// 断开远程共享文件夹
    /// </summary>
    /// <param name="remotePath"></param>
    /// <returns></returns>
    public static int Disconnect(string remotePath)
    {
    try
    {
    //必须是\\127.0.1.1\test格式,最后不能带斜杠
    if (remotePath.EndsWith("\\"))
    {
    remotePath = remotePath.Substring(0, remotePath.Length - 1);
    }
    int status = WNetCancelConnection2A(remotePath, 1, 1);
    return status;
    }
    catch (Exception ex)
    {
    return 0;
    }
    }

    /// <summary>
    /// 错误信息
    /// </summary>
    /// <param name="status"></param>
    /// <returns></returns>
    public static string GetErrorString(int status)
    {
    string strDesc = string.Empty;
    switch (status)
    {
    case 0:
    strDesc = "Success";
    break;
    case 5:
    strDesc = "网络访问拒绝";
    break;
    case 86:
    case 1326:
    strDesc = "无效的用户名或密码";
    break;
    case 1203:
    strDesc = "无效的网络路径";
    break;
    case 1219:
    strDesc = "提供的凭据与已存在的凭据集冲突";
    break;
    default:
    strDesc = "无法连接网络路径,错误代码:";
    break;
    }
    return strDesc;
    }

    /// <summary>
    /// cmd命令删除本机网络磁盘缓存用户
    /// </summary>
    public static void DelCacheUser()
    {
    try
    {
    string strCommand = @"NET USE * /DELETE /Y";
    Process p = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = "/C " + strCommand;
    startInfo.UseShellExecute = false;
    startInfo.RedirectStandardInput = false;
    startInfo.RedirectStandardOutput = true;
    startInfo.CreateNoWindow = true;
    p.StartInfo = startInfo;
    p.Start();
    p.Close();
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    }

    就这???! 就这。。

  • 相关阅读:
    HTML5触摸屏touch事件使用介绍1
    hdu 1408 acdearm &quot;Money, Money, Money&quot;
    基于QTP的自己主动化測试框架介绍
    ExpandListView onChildClickListener 失效
    hdu1227 Fast Food
    Linux C高级编程——文件操作之系统调用
    nodejs之路-[0]安装及简易配置
    动态加入改动删除html表格内容
    socket网络编程基础小记
    LeetCode OJ Minimum Depth of Binary Tree 递归求解
  • 原文地址:https://www.cnblogs.com/tianxujun/p/16371478.html
Copyright © 2020-2023  润新知