博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
指定账户访问共享文件
阅读量:6759 次
发布时间:2019-06-26

本文共 7015 字,大约阅读时间需要 23 分钟。

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

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

 

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);    }    ///     /// 获取共享目录下的文件名    ///     /// 共享目录:"\\192.168.1.110\project"    ///     ///     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 + "
"); } } }}

 

  

 

 2>

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>

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;using System.Diagnostics;/// ///FileShare 的摘要说明/// 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);        }    }}

  程序员的基础教程:

转载地址:http://caweo.baihongyu.com/

你可能感兴趣的文章
auto,register,static分析
查看>>
百度BAE JAVA环境项目部署和调试
查看>>
CSS盒模型
查看>>
Log4Net 添加自定义字段并保存到数据库
查看>>
Redis集群(三)Cluster集群
查看>>
NSURLSession
查看>>
JFinal学习 & Gradle配置续 & Tomcat配置
查看>>
CSS进度条
查看>>
android的color值
查看>>
对于linux下system()函数的深度理解(整理)
查看>>
软件设计和开发准备
查看>>
ROS + Kinect2 跑ORB_SLAM2 安装步骤记录
查看>>
纯CSS实现垂直居中的几种方法
查看>>
win7注册表常用设置
查看>>
amazeui学习笔记--css(常用组件3)--按钮组Button-group
查看>>
Spring简介
查看>>
new Function()
查看>>
man page分類與說明
查看>>
站立会议3
查看>>
Libvirt 版本降级过程记录 4.5.0 to 3.9.0
查看>>