使用 .NET 5 访问共享文件夹

本文将介绍如何使用 .NET 5 框架访问共享文件夹,并提供示例代码和相关说明。

访问步骤

  1. 引入必要命名空间:
using System.IO.Compression.FileSystem;
using System.Net.NetworkInformation;
  1. 检查共享文件夹是否存在:
if (Directory.Exists(sharedFolderPath))
{
    // ...
}
  1. 测试网络连接:
Ping ping = new Ping();
PingReply pingReply = ping.Send(sharedFolderPath);
if (pingReply.Status == IPStatus.Success)
{
    // ...
}
  1. 获取共享文件夹中的文件:
string[] files = Directory.GetFiles(sharedFolderPath);
foreach (string file in files)
{
    // ...
}

代码示例

using System;
using System.IO.Compression.FileSystem;
using System.Net.NetworkInformation;

namespace AccessSharedFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            string sharedFolderPath = @'\ComputerName\SharedFolderName';
            string localFolderPath = @'C:\LocalFolderName';
            string zipFilePath = @'C:\ZipFileName.zip';

            if (Directory.Exists(sharedFolderPath))
            {
                Ping ping = new Ping();
                PingReply pingReply = ping.Send(sharedFolderPath);
                if (pingReply.Status == IPStatus.Success)
                {
                    string[] files = Directory.GetFiles(sharedFolderPath);
                    foreach (string file in files)
                    {
                        // 将文件从共享文件夹复制到本地文件夹
                        File.Copy(file, Path.Combine(localFolderPath, Path.GetFileName(file)), true);
                    }

                    // 创建本地文件夹的压缩文件
                    ZipFile.CreateFromDirectory(localFolderPath, zipFilePath);
                    Console.WriteLine('Zip file created successfully!');
                }
                else
                {
                    Console.WriteLine('The computer hosting the shared folder is not reachable.');
                }
            }
            else
            {
                Console.WriteLine('The shared folder does not exist.');
            }

            Console.ReadLine();
        }
    }
}

权限管理

在访问共享文件夹时,请确保当前用户具有足够的权限。如果您的代码没有权限访问共享文件夹,可以使用 System.Net.NetworkCredential 类提供有效的用户名和密码来进行身份验证。

总结

本文介绍了如何使用 .NET 5 框架访问共享文件夹,并提供了示例代码和相关说明。希望本篇文章能够帮助您轻松实现文件共享和操作。

使用 .NET 5 访问共享文件夹 | C# 代码示例

原文地址: https://www.cveoy.top/t/topic/oUjR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录