1. 访问公共盘,可以用c#操作net use命令。(本人试验过,貌似只有这种方式可以用)
适用环境:当要访问公司别的部门的公共盘,又没有权限的时候。需要知道公共盘的IP,别的部门的一个账号密码。
public string ConnectLan(string p_Path, string p_UserName, string p_PassWord)
{
System.Diagnostics.Process _Process = new System.Diagnostics.Process();
_Process.StartInfo.FileName = "cmd.exe";
_Process.StartInfo.UseShellExecute = false;
_Process.StartInfo.RedirectStandardInput = true;
_Process.StartInfo.RedirectStandardOutput = true;
_Process.StartInfo.CreateNoWindow = true;
_Process.Start();
_Process.StandardInput.WriteLine("net use " + p_Path + " " + p_PassWord + " /user:" + p_UserName);
_Process.StandardInput.WriteLine("exit");
_Process.WaitForExit();
string _ReturnText = _Process.StandardOutput.ReadToEnd();// 得到cmd.exe的输出
_Process.Close();
return _ReturnText;
}<pre class="csharp" name="code">public string DeleteLan(string p_Path)
{
System.Diagnostics.Process _Process = new System.Diagnostics.Process();
_Process.StartInfo.FileName = "cmd.exe";
_Process.StartInfo.UseShellExecute = false;
_Process.StartInfo.RedirectStandardInput = true;
_Process.StartInfo.RedirectStandardOutput = true;
_Process.StartInfo.CreateNoWindow = true;
_Process.Start();
_Process.StandardInput.WriteLine("net use "+p_Path+" /del");
_Process.StandardInput.WriteLine("exit");
_Process.WaitForExit();
string _ReturnText = _Process.StandardOutput.ReadToEnd();// 得到cmd.exe的输出
_Process.Close();
return _ReturnText;
}
以上两个分别是连接公共盘,和取消连接公共盘。
用的时候注意先取消连接,再连接,用完之后再取消连接。因为如果连接过,又没有取消连接,当再次连的时候可能会连不上去。不允许多个用户同时连接。
2. 打印pdf文档用PrintDocument和Process
private void pdfPrint(string filePath)
{
PrintDocument pd = new PrintDocument();
if(!PrinterExists(pd))
{
MessageBox.Show("当前打印机不可用,请确认打印机是否正确!");
return;
}
p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = true;
startInfo.FileName = filePath;
startInfo.Verb = "print";
startInfo.Arguments = @"/p /h \" + filePath + "\"\"" + pd.PrinterSettings.PrinterName + "\"";
p.StartInfo = startInfo;
p.Start();
//pd.EndPrint += pd_EndPrint;
}
private bool PrinterExists(PrintDocument pd)
{ //判断打印机是否存在
string strDefaultPrinter = pd.PrinterSettings.PrinterName; //获取默认的打印机名
PrinterSettings.StringCollection snames = PrinterSettings.InstalledPrinters;
foreach (string s in snames)
{
if (s.ToLower().Trim() == strDefaultPrinter.ToLower().Trim())
{
return true;
}
}
return false;
}
其中函数PrinterExists是判断当前打印机是否存在。
这只是简单的判断,复杂点、更全面的自行扩展。
3. 用法
private void button_Print_Click(object sender, EventArgs e)
{
try
{
DeleteLan(strIPpath);
ConnectLan(strIPpath, "userName", "Password");
List<string> fileNames = GetAllPDFFiles();
for (int i = 0; i < fileNames.Count; i++)
{
pdfPrint(fileNames[i]);
}
DeleteLan(strIPpath);
}
catch
{
DeleteLan(strIPpath);
MessageBox.Show("未找到图纸,或打印机选择错误!");
}
}