Linux和Csharp,检查文件/文件夹是否存在于Linux中,如果存在,请通过Csharp SSH运行MKDIR -

时间:2016-02-11 03:53:39

标签: c# linux ssh

使用SSH.Net我想执行以下操作:通过C#和各种ssh软件包和/或winscp库创建命令以检查Linux机器上是否存在该文件,以及文件或文件是否存在于linux机器,然后它会创建它们,我喜欢编程的教育方面,所以我正在改进自我,我为没有完全写出问题而道歉。

private void TestCommmand(string ip, int port, string uname, string pw)
{
    // [1]
    SshClient cSSH = new SshClient(ip, port, uname, pw);
    cSSH.Connect();
    SshCommand x = new SshCommand();
    // [2] here is where the Check needs to happen
    //
    if (condition == true)
    {
        x = cSSH.RunCommand(" mkdir /var/www/html/app/cs");
    }
    else // if condition is false
    {
        cSSH.Disconnect();
        cSSH.Dispose();
    }
    //
}

2 个答案:

答案 0 :(得分:1)

如果目录及其父目录不存在,您可以mkdir -p /var/www/html/app/cs创建目录。

只要您有权创建第一个不存在的目录,该命令就会成功。如果仅存在/var/www,则会创建html,然后app,然后cs。如果存在/var/www/html/app/cs,则无效。

所以你的代码就是:

private void TestCommmand(string ip, int port, string uname, string pw)
{
    SshClient cSSH = new SshClient(ip, port, uname, pw);
    cSSH.Connect();
    SshCommand x = new SshCommand();
    x = cSSH.RunCommand("mkdir -p /var/www/html/app/cs");
    /// .. Continue with your work ...
}

请注意,您应该在几乎每一步之后检查错误:SSH连接可能失败,命令因权限而失败等等...

答案 1 :(得分:1)

这是我不久前遇到的事情,所以请相信我......

让我们看看下面这个小家伙:

if(condition == true) 

在某种程度上,你已经回答了你的问题,只是不理解语法。 (检查

using System;
using System.IO;

namespace StackOverflowQA
{
    class Program
     {

         static void Main(string[] args)
         {
            if(File.Exists(@"C:\Exercise\Derp\"))
             {
               DoWork();
             }
             else
             {
               Console.Out.Writelne("Wrong kid died");
               Console.Write("Enter a key to exit");
               Console.Read();
             }

            private static void DoWork()
            {

              //-- if you get to this point then check out that,
             //    NuGet pkg you're working with (WinSCP) and proceed! :) 
            }
         }

      }
 }

在进入第三方程序集或库/之前,我认为您需要先创建一个简单的控制台应用程序来查找计算机上的文件。

创建我刚刚在代码中描述的文件夹和“DoWork();”

干杯^ _ ^