posts - 710,  comments - 81,  views - 260万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

访问共享文件夹的方法有很多

1>这边在本地测试通过,用这个方法不是用net use命令模拟,而是类似credential来装扮一个权限的账户来访问网络路径的文件。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
using System.Runtime.InteropServices;
using System.IO;
 
public class FromSharedFoldersInDomain : IDisposable
{
 
    // obtains user token   
    [DllImport("advapi32.dll", SetLastError = true)]
    static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
 
    // closes open handes returned by LogonUser   
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    extern static bool CloseHandle(IntPtr handle);
 
    [DllImport("Advapi32.DLL")]
    static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
 
    [DllImport("Advapi32.DLL")]
    static extern bool RevertToSelf();
    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域的需要癮用:Interactive = 2   
    private bool disposed;
    public FromSharedFoldersInDomain(string sUsername, string sDomain, string sPassword)
    {
        // initialize tokens   
        IntPtr pExistingTokenHandle = new IntPtr(0);
        IntPtr pDuplicateTokenHandle = new IntPtr(0);
 
        try
        {
            // get handle to token   
            bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
                LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);
 
            if (true == bImpersonated)
            {
                if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
                }
            }
            else
            {
                int nErrorCode = Marshal.GetLastWin32Error();
                throw new Exception("LogonUser error;Code=" + nErrorCode);
            }
        }
        finally
        {
            // close handle(s)   
            if (pExistingTokenHandle != IntPtr.Zero)
                CloseHandle(pExistingTokenHandle);
            if (pDuplicateTokenHandle != IntPtr.Zero)
                CloseHandle(pDuplicateTokenHandle);
        }
    }
 
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            RevertToSelf();
            disposed = true;
        }
    }
 
    public void Dispose()
    {
        Dispose(true);
    }
 
    /// <summary>
    /// 获取共享目录下的文件名
    /// </summary>
    /// <param name="remotePath">共享目录:"\\192.168.1.110\project"</param>
    /// <param name="userName"></param>
    /// <param name="userPassword"></param>
    public static void GetFiles(string remotePath, string userName, string userPassword)
    {
        using (FromSharedFoldersInDomain iss = new FromSharedFoldersInDomain(
          userName, remotePath, userPassword))
        {
            DirectoryInfo Dir = new DirectoryInfo(remotePath);
            foreach (FileInfo item in Dir.GetFiles())
            {
                HttpContext.Current.Response.Write(item.Name + "<br/>");
            }
        }
    }
}

 

  

 

 2>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
string localpath = "X:";
        string serverPath = @"\\192.168.199.173\Project";
        string loginUser = "administrator";
        string loginPassword = "430016";
        int status = NetworkConnection.Connect(serverPath, localpath, loginUser, loginPassword);
        if (status == (int)ERROR_ID.ERROR_SUCCESS)
        {
            FileStream fs = new FileStream(localpath + @"\123.txt", FileMode.OpenOrCreate);
            using (StreamWriter stream = new StreamWriter(fs))
            {
                stream.WriteLine("你好呀,成功了");
                stream.Flush();
                stream.Close();
            }
            fs.Close();
        }
        else
        {
            Console.WriteLine(status);
        }
        NetworkConnection.Disconnect(localpath);

  

3>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
using System.IO;
using System.Diagnostics;
 
/// <summary>
///FileShare 的摘要说明
/// </summary>
public class FileShare
{
    public FileShare() { }
 
    public static bool connectState(string path)
    {
        return connectState(path, "administrator", "430016");
    }
 
    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 = string.Format("net use \"{0}\" /User:{1} {2} /PERSISTENT:YES", path, userName, passWord);
            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;
    }
 
 
    //read file
    public static void ReadFiles(string path)
    {
        try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader(path))
            {
                String line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
 
                }
            }
        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
 
    }
 
    //write file
    public static void WriteFiles(string path)
    {
        try
        {
            // Create an instance of StreamWriter to write text to a file.
            // The using statement also closes the StreamWriter.
            using (StreamWriter sw = new StreamWriter(path))
            {
                // Add some text to the file.
                sw.Write("This is the ");
                sw.WriteLine("header for the file.");
                sw.WriteLine("-------------------");
                // Arbitrary objects can also be written to the file.
                sw.Write("The date is: ");
                sw.WriteLine(DateTime.Now);
            }
        }
        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

  程序员的基础教程:菜鸟程序员

posted on   itprobie-菜鸟程序员  阅读(829)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2014-12-03 adf 日志输出
点击右上角即可分享
微信分享提示