计算C#中复制文件的数量

时间:2016-01-18 11:24:04

标签: c#

我有一个我要复制文件的计算机列表。

我正在尝试创建一个标签,显示当时正在复制的计算机。例如:“复制到computer1 ...(x of 10)”,其中10基于字符串数组中的行数:

var lineCount = File.ReadLines(complist).Count();

每次复制新文件时,如何更改第一个数字(x)? (1 of 10),(2 of 10)等...

以下是我的标签:

label2.Text = ("Copying to " + @computer + "... ( of " + lineCount + ")");

编辑:这是我的复制操作。文件将复制到每个远程系统。

        string complist = openFileDialog2.FileName;
        string patch = textBox2.Text;
        string fileName = patch;
        string patchfile = Path.GetFileName(fileName);
        var lineCount = File.ReadLines(complist).Count();

        foreach (string line in File.ReadLines(complist))
        {
            //Checks if C:\PatchUpdates exists on remote machine. If not, a folder is created.
            if (!Directory.Exists(@"\\" + line + @"\C$\PatchUpdates"))
            {
                Directory.CreateDirectory(@"\\" + line + @"\C$\PatchUpdates");
            }

            //XCOPY patch to every computer
            System.Diagnostics.Process processCopy = new System.Diagnostics.Process();
            ProcessStartInfo StartInfo = new ProcessStartInfo();
            StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            StartInfo.FileName = "cmd";
            StartInfo.Arguments = string.Format("/c xcopy " + patch + " " + @"\\{0}\C$\PatchUpdates /K /Y", line);
            processCopy.StartInfo = StartInfo;
            processCopy.Start();
            label2.Text = ("Copying to " + @line + "... (" + @num + " of " + @lineCount + ")");
            processCopy.WaitForExit();

3 个答案:

答案 0 :(得分:1)

只需将num声明为变量并在循环中递增它:

int num = 0;

foreach (string line in File.ReadLines(complist))
{
    num++;

    //...
    label2.Text = ("Copying to " + line + "... (" + num + " of " + lineCount + ")"); 
    //..
}  

顺便说一下,你正在读取文件中的两行。一旦你得到行数和另一个时间来获得行。

如果你有一个大文件并且你不想一次读取所有行(对于内存问题),使用ReadLines会更好。但是,如果文件相对较小,那么您只需使用ReadAllLines读取文件行一次,并将它们存储在如下变量中:

var lines = File.ReadAllLines(complist);

var lineCount = lines.Length;

int num = 0;

foreach (string line in lines)
{
    num++;
    //...
}

答案 1 :(得分:0)

只要保留每次进入下一行时增加的索引。

int num = 0;
foreach (string line in File.ReadLines(complist))
{
  ++num;
  string progress = string.Format("Copying to {0} ({1} of {2})", line, num, lineCount);
  // ...

我保留了您的变量名称,但我强烈建议比linenum更好(比如computerNamecomputerIndex)。

或者,你可以用一个老式的foreach循环替换for,这基本上颠倒了整个事物:

var lines = File.ReadLines(complist);
for (int num = 0; num < lineCount; ++num)
{
  string line = lines[num];
  string progress = string.Format("Copying to {0} ({1} of {2})", line, num, lineCount);
  // ...

答案 2 :(得分:0)

for(int i = 0; i < lineCount; i ++)
{
    label2.Text = string.Format(@"Copying to {0} ({1} of {2})", complist[i], i + 1, lineCount;
    // Copy logic ... 
}