2014-07-16 38 views
-1

我正在尝试更改一系列4个.bat文件。当我运行该程序时,它会提示我输入,然后将其写入.bat文件。用循环编辑参数

我从File.Openwrite的微软文档下面的代码,然后添加一些变量指向文件。

与复制/粘贴实际写入文本的代码相反,我在其周围放置了一个for循环,目的是改变参数,以便File.OpenWrite片断将查找不同的变量(并且不同的变量路径/目录)。我证实了循环的作用(如果我输入其中一个路径#变量,它将遍历并向该文件写入4次),并且File.OpenWrite每次迭代都会看到正确的文本。我唯一的猜测是,它正在逐字查看'path#'参数,并没有将其视为变量。有人能帮助我理解我如何通过迭代改变这个论点吗?

using System; 
using System.IO; 
using System.Text; 

class Test 
{ 
    public static void Main() 
    { 
     string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
     string path0 = path + @"\down_fa.bat"; 
     string path1 = path + @"\down_ng.bat"; 
     string path2 = path + @"\down_os.bat"; 
     string path3 = path + @"\down_sp.bat"; 
     string portinput = Console.ReadLine(); 
     string dotbatinput = "DDL -p" + portinput; 

     // Open the stream and write to it. 

     for (int i = 0; i < 4; i++) 
     { 

      using (FileStream fs = File.OpenWrite("path" + i)) 
      { 
       Byte[] info = 
        new UTF8Encoding(true).GetBytes(dotbatinput); 

       // Add some information to the file. 
       fs.Write(info, 0, info.Length); 
      } 
     } 

    } 
} 
+0

你的猜测是正确的 – Steve

+0

只要把一个数组和循环所有走过的路径相反。 –

回答

0
File.OpenWrite("path" + 0) != File.OpenWrite(path0) 

左侧打开一个流一个名为“PATH0”,您将在bin\Debug目录中的项目和正确的示例中找到文件在字符串path0在指定的位置写入文件。当然也适用于其他号码。一种可能的解决办法是使用数组或列表:

string[] paths = new string[4].Select(x => System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)).ToArray(); 
string[0] += ...; 
string[1] += ...; 
string[2] += ...; 
string[3] += ...; 

foreach (string path in paths) 
{ 
    using (FileStream fs = File.OpenWrite(path)) 
    { 
     // do stuff 
    } 
} 
0

你不能指的是使用一个字符串,并串联了一些在你的代码中声明的变量。通过这种方式,您可以将文字字符串传递给OpenWrite方法,而不是名称与您的字符串相同的变量的内容。

更简单的方法是将每一个批处理文件添加到字符串列表,然后遍历该列表内容写入所需

string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
List<string> batFiles = new List<string>(); 
batFiles.Add(System.IO.Path.Combine(path, "down_fa.bat")); 
batFiles.Add(System.IO.Path.Combine(path, "down_ng.bat")); 
batFiles.Add(System.IO.Path.Combine(path, "down_os.bat")); 
batFiles.Add(System.IO.Path.Combine(path, "down_sp.bat")); 
string portinput = Console.ReadLine(); 
string dotbatinput = "DDL -p" + portinput; 

foreach(string batFile in batFiles) 
{ 
    using (FileStream fs = File.OpenWrite(batFile)) 
    { 
    ----- 
    } 
}