user2536008 user2536008 - 3 months ago 13
C# Question

Loop through a string array and pass its elements to a method

I have a c# console application that copies files from different directories on the network and place them in one single location on the server (Win Server 2008 R2). When I run the application, I get "File not found - System.String[] 0 File(s) copied." message.

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

}


We have around 15 directories to loop through.

Answer

This is the problem:

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

You should be using d inside the foreach:

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

You then need to change the xcopy method to take in a string instead of a string[].

When you do the following:

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

You are converting the String[] to a String (the runtime will call .ToString() on SrcLoc). This is how it ends up with System.String[] in your process arguments.


Also, this block of code does nothing except destroy the stack trace.

catch (Exception exp)
{
    throw exp;
}

If you want to re-throw and error, you should just do throw;.

Comments