歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C# 向共享文件中寫入數據

C# 向共享文件中寫入數據

日期:2017/3/1 9:48:27   编辑:Linux編程

先寫一個判斷此時是否可以正常連接網絡共享主機:

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

Copyright © Linux教程網 All Rights Reserved