指定账户访问共享文件

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

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);
    }

    /// <summary>
    /// 获取共享目录下的文件名
    /// </summary>
    /// <param name="remotePath">共享目录:"\192.168.1.110project"</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>

string localpath = "X:";
        string serverPath = @"\192.168.199.173Project";
        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;

/// <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);
        }
    }
}

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

原文地址:https://www.cnblogs.com/guohu/p/5015844.html