先写一个判断此时是否可以正常连接网络共享主机:
private static bool connectState()
{
bool flag = false;
Process process = new Process();
try
{
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string dosLine = @"net use \\IP_ADDRESS\PATH /User:username password /PERSISTENT:YES";
process.StandardInput.WriteLine(dosLine);
process.StandardInput.WriteLine("exit");
while (!process.HasExited)
{
process.WaitForExit(1000);
}
string errorMsg = process.StandardError.ReadToEnd();
process.StandardError.Close();
if (String.IsNullOrEmpty(errorMsg))
{
flag = true;
}
else
{
throw new Exception(errorMsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
process.Close();
process.Dispose();
}
return flag;
}
上面的这一段代码是摘抄的, 当然这一段就是访问网络文件的核心了,之后就是正常的操作文件了(仅限局域网)我的是这样子的,很简单的一个:
public static void logs(string str)
{
using (FileStream fs = new FileStream("//IP_ADDRESS/PATH/hook.txt", FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(str);
}
}
}