c#使用账户密码 访问共享文件夹文件
时间: 2024-02-05 16:05:23 浏览: 263
C#访问共享文件夹
5星 · 资源好评率100%
如果共享文件夹需要使用账户密码才能访问,你可以使用 NetworkCredential 类来指定访问共享文件夹的账户和密码。例如:
```
string path = @"\\COMPUTER_NAME\SHARED_FOLDER\file.txt";
NetworkCredential credential = new NetworkCredential("USERNAME", "PASSWORD");
FileInfo file = new FileInfo(path);
// 使用账户密码访问文件
using (new NetworkConnection(Path.GetDirectoryName(path), credential))
{
string content = File.ReadAllText(file.FullName);
}
```
其中,NetworkConnection 是一个自定义类,用于创建网络连接并使用指定的凭据进行身份验证。你需要在代码中添加以下代码:
```
class NetworkConnection : IDisposable
{
string _networkName;
public NetworkConnection(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var result = WNetAddConnection2(netResource, credentials.Password, credentials.UserName, 0);
if (result != 0)
{
throw new Win32Exception(result);
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags, bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
```
需要注意的是,这段代码使用了 WNetAddConnection2 和 WNetCancelConnection2 API 函数来创建和取消网络连接。因此,你需要在代码中添加 `using System.Runtime.InteropServices;` 来引用该命名空间。
阅读全文