无法获取共享文件夹原始文件(系统路径)

时间:2019-09-06 08:39:02

标签: c#

获取共享文件夹系统路径但代码 返回相同的路径共享文件夹,例如“ @ \ 123.1.1.56 \ Pagal”

DirSearch("\\\\DESKTOP-2FFGFDM\\Packages");

static void DirSearch(string dir, string rootDir = null)
{

    if (rootDir == null)
    {
        rootDir = dir;
    }
    try
    {
        foreach (string f in Directory.GetFiles(dir))
        {
            string filename = f.Substring(rootDir.Length);
            Console.WriteLine(filename);
        }
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(d);
            DirSearch(d, rootDir);
        }

    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

我找不到共享文件夹系统路径 如此。帮我......... 在此先感谢

1 个答案:

答案 0 :(得分:1)

要测试是否存在网络共享,可以使用DirectoryInfo

static void DirSearch(string dir, string rootDir = null)
{
    if(!new DirectoryInfo(dir).Exists)
      throw new Exception($"the provided directory {dir} is not valid.")

    if (rootDir == null)
    {
        rootDir = dir;
    }
    try
    {
        foreach (string f in Directory.GetFiles(dir))
        {
            string filename = f.Substring(rootDir.Length);
            Console.WriteLine(filename);
        }
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(d);
            DirSearch(d, rootDir);
        }

    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

如果这是递归编程的学校作业,那将是可行的,但是您只需要获取所有文件和directory without the recursion

foreach (string f in Directory.GetFiles(dir,"*.*",SearchOption.AllDirectories))
{
     string filename = f.Substring(rootDir.Length);
     Console.WriteLine(filename);
}

这些文件来自目录,因此您可以从名称中删除这些文件

var dir="";
foreach (string f in Directory.GetFiles(dir,"*.*",SearchOption.AllDirectories))
{
    string filename = f.Substring(rootDir.Length);
    var directoryName = new FileInfo(filename).Directory.FullName;
    if(directoryName!=dir)
    {
      Console.WriteLine(filename);
      dir= directoryName ;
    }
    Console.WriteLine(filename);
}