循环遍历字符串数组,并将其元素传递给方法

本文关键字:元素 方法 字符串 遍历 数组 循环 | 更新日期: 2023-09-27 18:00:12

我有一个c#控制台应用程序,它可以从网络上的不同目录复制文件,并将它们放在服务器上的一个位置(Win server 2008 R2)。当我运行应用程序时,我会收到"找不到文件-System.String[]0个文件已复制。"消息。

static void Main(string[] args)
    {
        string[] srcPath =
            {
              @"''sharedloc1'HR'Org Docs",
              @"''sharedloc2'MKT'Org Docs"
            };
        string desPath = @"C:'Users'James'Desktop'my docs";
        foreach (string d in srcPath)
        {
            xcopy(srcPath, desPath + @"'");
        }
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
    private static void xcopy(string[] SrcLoc, string FnlLoc)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "copyFiles";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "'"" + SrcLoc + "'"" + " " + "'"" + FnlLoc + "'"" + @" /d /y";
        try
        {
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch (Exception exp)
        {
            throw exp;
        }
    }

我们有大约15个目录可以循环浏览。

循环遍历字符串数组,并将其元素传递给方法

这就是问题所在:

foreach (string d in srcPath)
{
    xcopy(srcPath, desPath + @"'");
}

您应该在foreach中使用d

foreach (string d in srcPath)
{
    xcopy(d, desPath + @"'");
}

然后,您需要更改xcopy方法以接受string而不是string[]

当您执行以下操作时:

startInfo.Arguments = "'"" + SrcLoc + "'"" + " " + "'"" + FnlLoc + "'"" + @" /d /y";

您正在将String[]转换为String(运行时将在SrcLoc上调用.ToString())。这就是它在流程参数中以System.String[]结束的方式。


此外,这段代码除了破坏堆栈跟踪之外什么也不做。

catch (Exception exp)
{
    throw exp;
}

如果你想重新抛出并出错,你应该只做throw;