合并文本文件名

时间:2016-06-03 03:14:58

标签: c# text-files

我有一个清单。

List<string> slots = HexStringToGenerateFiles(weaponStorageEntity.Slot);

我正在使用foreach循环检索列表,并同时进行了一些转换。

string slotnumber = "";
string ibuttonslot = "";
foreach (string slot in slots)
{
 slotnumber += slot;
 ibuttonslot = ByteOperation.ReverseString((Convert.ToString(1 << ((Int32.Parse(slotnumber)) - 1), 2).PadLeft(16, '0')));
}

然后,将输出保存为文本文件的名称。

  CreateFile(String.Format("{0}\\B_{1:X16}.TXT",
                                   userDir,
                                   ibuttonslot,
                                   ));

如果我有3个插槽,那么我的输出将有3个文本文件。但是,我希望它只是一个文本文件组合。我的输出如下所示。

  

B_10000000.TXT

     

B_01000000.TXT

     

B_00100000.TXT

我想要的输出是

  

B_11100000.TXT

3 个答案:

答案 0 :(得分:1)

如果您的插槽编号为&#34; 1&#34;,&#34; 2&#34;,&#34; 3&#34;,...并且想要生成文件名这将代表&#34; 1&#34;在相应的插槽中 - 所以对于&#34; 1 3&#34;它将是10100000 ...那么你可以使用这样的东西:

var slots = new[] { "1" };
var number = 0; 
foreach (var s in slots)
{
    int slotNumber;
    if (!Int32.TryParse(s, out slotNumber)) continue;

    var slot = (int)Math.Pow(2, slotNumber - 1);
    number |= slot;
}

var fileName = Convert.ToString(number, 2).PadLeft(16, '0');
Console.WriteLine(fileName); //output is 0000000000000101

然后恢复此字符串(在您的代码中为ByteOperation.ReverseString)。

答案 1 :(得分:0)

如果你想要合并两个文件的文本,那么你可以使用File.ReadAllLines(string)方法并将输出结合起来像

        List<string> contents = System.IO.File.ReadAllLines(firstfile).ToList();
        contents.AddRange(System.IO.File.ReadAllLines(secondfile));

答案 2 :(得分:0)

您可以尝试将其组合起来:

string in1 = "B_10000000.TXT";
string in2 = "B_01000000.TXT";
string in3 = "B_00100000.TXT";
char[] charsInName = in1.ToCharArray();
for (int i = 0; i < charsInName.Length-1; i++)
{
    if (charsInName[i] != in2[i] && charsInName[i] != in3[i])
        charsInName[i] = charsInName[i];
    else if (charsInName[i] != in2[i])
        charsInName[i] = in2[i];
    else if (charsInName[i] != in3[i])
        charsInName[i] = in3[i];
}
string outPutName = String.Join("", charsInName);// will be B_11100000.TXT

或者可以使用LINQ:

var result = in1.Select(
    (x, y) => x != in2[y] && x != in3[y] ? x :
    x != in2[y] ? in2[y] : 
    x != in3[y] ? in3[y] : x);
string outPutName = String.Join("", result);