首先是设置共享目录,支持用户和密码等权限控制
然后我们可以使用Windows资源管理器操作共享目录下的文件
这中间隐藏了资源管理器帮我们建立目录映射和连接的过程,如果设置了用户名和密码,在进入目录前就需要输入验证。
如何以代码的方式实现
共享目录最终的操作是跟本地目录一致的,代码实现主要就是为了完成目录映射和连接的建立和关闭。这一过程可以通过COM调用实现。
- 首页建立跟网络目录的连接
- 在共享下的操作内容
- 使用完成后关闭练级
调用封装
// 打开连接[DllImport("mpr.dll", EntryPoint = "WNetAddConnection2")]private static extern uint WNetAddConnection2(NetResource lpNetResource, string lpPassword, string lpUsername, uint dwFlags);// 关闭连接[DllImport("Mpr.dll", EntryPoint = "WNetCancelConnection2")]private static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool fForce);
使用示例
try{ uint result = WNetConnectionHelper.WNetAddConnection(_UserName, _Passeord, _ShareDefaultPath, null); using (FileStream fs = File.Open(Path.Combine(_ShareDefaultPath, "withmiao.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { // 向文件追加时间戳 using (StreamWriter sw = new StreamWriter(fs)) { // 设置到行尾 sw.BaseStream.Position = sw.BaseStream.Length; sw.WriteLine(DateTime.Now.ToString()); sw.Close(); } fs.Close(); }}catch (Exception ex){ throw ex;}finally{ // 完成后关闭连接 uint nColse = WNetConnectionHelper.WNetCancelConnection(_UserName, 1, true);}