怎么用C#访问共享文件夹

求救一个问题。我想通过C#访问其他计算机的共享文件夹。IP:192.168.1.1用户名:administrator密码:123SecureStringpassword=... 求救一个问题。我想通过C#访问其他计算机的共享文件夹。IP:192.168.1.1 用户名:administrator 密码:123
SecureString password = new SecureString();
foreach (char c in this.textBox1.Text.ToCharArray())
password.AppendChar(c); Process.Start(@"\\192.168.15.90","administrator",password,"?")

我画问号的那个地方应该怎么写啊,提示说是应该写域名可是我没有域。还有就是password好像也有问题。好像也不对。求高手指点下
展开
 我来答
wdghy123
2015-08-15 · TA获得超过1583个赞
知道大有可为答主
回答量:1514
采纳率:95%
帮助的人:733万
展开全部

    用C#访问共享目录总是出现权限问题,让人很头疼,研究了很久找到一种办法,贴上代码:

 public class IdentityScope : 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 IdentityScope(string sUsername,string sPassword, string sDomain)    
        {    
            // 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);    
        }    
    }

通过IdentityScope传入目标机器的IP,用户名和密码就可以访问到共享目录了。

如何使用如下:

using (IdentityScope iss = new IdentityScope(targetLoginName, targetPassword,targetIP))
 {
           //你的代码        
 }
保雨珍pr
推荐于2016-06-16 · TA获得超过160个赞
知道小有建树答主
回答量:252
采纳率:0%
帮助的人:138万
展开全部
public static bool Connect(string remoteHost, 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 = "net use " + remoteHost + " " + passWord + " /user:" + userName;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit(1000);
}

string errormsg = proc.StandardError.ReadToEnd();
WriteLog.WirteDayLog("msg:" + errormsg);
proc.StandardError.Close();
if (String.IsNullOrEmpty(errormsg))
{
Flag = true;
}
}
catch (Exception ex)
{
WriteLog.WirteDayLog(ex.ToString());
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
}
Connect(@"\\192.168.15.90", "administrator", "123")
追问
程序我运行了但是没有任何反应。我想要打开共享的文件夹。我在程序里有些了个
string dosLine1 = "explorer " + remoteHost; proc.StandardInput.WriteLine(dosLine1);就好了。但是有个代码我没不知道是啥 ,WriteLog是啥啊。在哪定义的

求高手在指点指点呗。谢谢
追答
WriteLog是我记错误日志的方法,你删掉就好了
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
百度网友363f40a
2013-12-02 · 超过44用户采纳过TA的回答
知道小有建树答主
回答量:194
采纳率:0%
帮助的人:113万
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
dong_1984dd
2015-08-30 · TA获得超过1.1万个赞
知道小有建树答主
回答量:1070
采纳率:100%
帮助的人:230万
展开全部
1、在服务器设置一个共享文件夹,服务器ip地址是10.80.88.180,共享文件夹名字是test,test里面有两个文件:good.txt和bad.txt,访问权限,用户名是admin,密码是admin。
2、新建一个webapplication项目,在前台页面加一个listbox,ID是ListBox1.
3、添加后台代码如下:其中包含的功能是读文件,这里以读good
文件为例;写文件,这里以写bad文件为例;还有是将test文件夹下的文件名列到listbox中。
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace
WebApplication2
{
public class FileShare
{
public FileShare() {
}
public static bool connectState(string path)//连接
{

return
connectState(path,"","");
}
//判断连接是否成功
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 =
@"net use " + path + " /User:" + userName + " " + passWord + "
/PERSISTENT:YES";

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

}

}

}

public partial class _Default :
System.Web.UI.Page
{

protected void
Page_Load(object sender, EventArgs e)

{

bool status =
false;

//连接共享文件夹

status =
FileShare.connectState(@"\\10.80.88.180\test", "admin",
"admin");

if
(status)

{

DirectoryInfo
theFolder = new DirectoryInfo(@"\\10.80.88.180\test");

//先测试读文件,把目录路径与文件名连接

string filename =
theFolder.ToString()+"\\good.txt";

FileShare.ReadFiles(filename);

//测试写文件,拼出完整的路径

filename =
theFolder.ToString() + "\\bad.txt";

FileShare.WriteFiles(filename);

//遍历共享文件夹,把共享文件夹下的文件列表列到listbox

foreach (FileInfo
nextFile in theFolder.GetFiles())
{

ListBox1.Items.Add(nextFile.Name);

}

}

else

{

ListBox1.Items.Add("未能连接!");

}

}

}}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式