C#读写局域网共享文件
时间: 2023-10-19 14:28:53 浏览: 63
您可以使用C#的System.IO命名空间来读写局域网共享文件。以下是一个简单的示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"\\server\share\file.txt"; // 共享文件的路径
string content = ReadFile(filePath); // 读取文件内容
Console.WriteLine(content);
string newContent = "Hello, World!";
WriteFile(filePath, newContent); // 写入新内容到文件
}
static string ReadFile(string filePath)
{
string content = string.Empty;
try
{
using (StreamReader sr = new StreamReader(filePath))
{
content = sr.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("读取文件出错:" + e.Message);
}
return content;
}
static void WriteFile(string filePath, string content)
{
try
{
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write(content);
}
}
catch (Exception e)
{
Console.WriteLine("写入文件出错:" + e.Message);
}
}
}
```
请注意,您需要将`filePath`替换为实际的共享文件路径,例如`\\server\share\file.txt`。确保您的程序具有足够的权限来访问和操作该共享文件。