C# 上传本地文件到远程共享文件夹,从远程共享文件夹下载文件到本地

        在访问远程机器的文件夹的时候,首先需要对文件夹设置访问权限,具体方法自己搜一下,最好不要把共享文件夹放在桌面上,很容易出现对路径无法访问的错误。下面就是代码了。我在网上查到很多人说这是对服务器的文件上传和下载,但是我觉得这和服务器没半毛钱关系,这就是一个局域网内的文件访问。

       在本地机器里的vs中新建一个C#控制台应用程序,添加如下代码,我是在远程电脑的D盘新建了一个共享文件夹Test2,然后在里面进行上传和下载操作的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            bool status = false;

            //连接共享文件夹
            status = connectState(@"\\192.168.2.144\Test2", "Admin", "123");
            if (status)
            {
                //共享文件夹的目录
                DirectoryInfo theFolder = new DirectoryInfo(@"\\192.168.2.144\Test2\");
                //获取保存文件的路径
                string PathName = theFolder.ToString();
                //执行方法
                Transport(@"D:\Test.txt", PathName, "4.txt");  //上传文件到另一台电脑的共享文件夹,需要设置共享文件夹的权限,共享文件夹不要设在桌面
                TransportRemoteToLocal(@"D:\Test2.txt", PathName, "2.txt");  //从另一电脑的共享文件夹下载文件到本机
            }
            else
            {
               
            }
            Console.ReadKey();
        }

        public static bool connectState(string path)
        {
            return connectState(path, "", "");
        }
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        /// <summary>
        /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        public static void Transport(string src, string dst, string fileName)
        {

            FileStream inFileStream = new FileStream(src, FileMode.Open);
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;

            if (!File.Exists(dst))
            {
                FileStream outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);


                byte[] buf = new byte[inFileStream.Length];

                int byteCount;

                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {

                    outFileStream.Write(buf, 0, byteCount);

                }

                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="src">下载到本地后的文件路径,包含文件的扩展名</param>
        /// <param name="dst">远程服务器路径(共享文件夹路径)</param>
        /// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
        public static void TransportRemoteToLocal(string src, string dst, string fileName)   //src:下载到本地后的文件路径  dst:远程服务器路径 fileName:远程服务器dst路径下的文件名
        {
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            FileStream inFileStream = new FileStream(dst, FileMode.Open);    //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错

            FileStream outFileStream = new FileStream(src, FileMode.OpenOrCreate);   //从远程服务器下载到本地的文件

            byte[] buf = new byte[inFileStream.Length];

            int byteCount;

            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {

                outFileStream.Write(buf, 0, byteCount);

            }

            inFileStream.Flush();

            inFileStream.Close();

            outFileStream.Flush();

            outFileStream.Close();

        }

    }
}

觉得有用的麻烦点个赞,谢谢!

你可以使用C#中的System.IO和System.Net命名空间来实现复制本地文件夹到共享文件夹的功能。以下是实现的基本步骤: 1. 使用Directory.GetFiles和Directory.GetDirectories方法获取本地文件夹中的文件和子文件夹。 2. 使用File.Copy方法将文件从本地文件夹复制到共享文件夹。 3. 使用Directory.CreateDirectory方法在共享文件夹中创建子文件夹。 4. 递归调用自己,将子文件夹中的文件文件夹复制到共享文件夹中。 以下是一个示例代码,可以将本地文件夹D:\LocalFolder复制到共享文件夹\\Server\SharedFolder: ```csharp using System.IO; using System.Net; public void CopyFolderToSharedFolder() { string localFolderPath = @"D:\LocalFolder"; string sharedFolderPath = @"\\Server\SharedFolder"; // Create a WebRequest instance for the shared folder WebRequest sharedFolderRequest = WebRequest.Create(sharedFolderPath); NetworkCredential credentials = new NetworkCredential("username", "password"); sharedFolderRequest.Credentials = credentials; // Get the response from the shared folder request WebResponse sharedFolderResponse = sharedFolderRequest.GetResponse(); // Get the shared folder stream and create a StreamWriter instance Stream sharedFolderStream = sharedFolderResponse.GetResponseStream(); StreamWriter sharedFolderWriter = new StreamWriter(sharedFolderStream); // Get the files and directories in the local folder string[] files = Directory.GetFiles(localFolderPath); string[] directories = Directory.GetDirectories(localFolderPath); // Copy the files to the shared folder foreach (string file in files) { // Get the filename from the file path string filename = Path.GetFileName(file); // Create the shared file path string sharedFilePath = Path.Combine(sharedFolderPath, filename); // Copy the file to the shared folder File.Copy(file, sharedFilePath); } // Copy the directories to the shared folder foreach (string directory in directories) { // Get the directory name from the directory path string directoryName = Path.GetFileName(directory); // Create the shared directory path string sharedDirectoryPath = Path.Combine(sharedFolderPath, directoryName); // Create the shared directory Directory.CreateDirectory(sharedDirectoryPath); // Recursively copy the files and directories in the local directory to the shared directory CopyFolder(directory, sharedDirectoryPath); } // Close the shared folder stream and response sharedFolderWriter.Close(); sharedFolderResponse.Close(); } private void CopyFolder(string sourceFolderPath, string targetFolderPath) { // Get the files and directories in the source folder string[] files = Directory.GetFiles(sourceFolderPath); string[] directories = Directory.GetDirectories(sourceFolderPath); // Copy the files to the target folder foreach (string file in files) { // Get the filename from the file path string filename = Path.GetFileName(file); // Create the target file path string targetFilePath = Path.Combine(targetFolderPath, filename); // Copy the file to the target folder File.Copy(file, targetFilePath); } // Copy the directories to the target folder foreach (string directory in directories) { // Get the directory name from the directory path string directoryName = Path.GetFileName(directory); // Create the target directory path string targetDirectoryPath = Path.Combine(targetFolderPath, directoryName); // Create the target directory Directory.CreateDirectory(targetDirectoryPath); // Recursively copy the files and directories in the source directory to the target directory CopyFolder(directory, targetDirectoryPath); } } ``` 在上面的代码中,我们首先使用WebRequest和NetworkCredential类设置访问共享文件夹所需的凭据。然后,我们使用Directory.GetFiles和Directory.GetDirectories方法获取本地文件夹中的文件和子文件夹,并使用File.Copy方法将文件从本地文件夹复制到共享文件夹。接下来,我们使用Directory.CreateDirectory方法在共享文件夹中创建子文件夹,并递归调用自己,将子文件夹中的文件文件夹复制到共享文件夹中。最后,我们关闭共享文件夹流和响应。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值