简体   繁体   中英

Combining text files name

I have a list.

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

I'm retrieving the list using foreach loop and did some conversion at the same time.

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

Then, save the output as a name of a textfile.

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

If I have 3 slots, then my output will have 3 textfiles. However, I would like it to combine it be one textfile only. My output is something as shown below.

B_10000000.TXT

B_01000000.TXT

B_00100000.TXT

My desired output is

B_11100000.TXT

If you have your slots numbered just as "1", "2", "3", ... and want to produce a name of the file that would represent "1" in a corresponding slot - so for "1 3" it would be 10100000... then you can use something like this:

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

And then revert this string (in your code it is ByteOperation.ReverseString).

If you want to combine both file's text then you can use File.ReadAllLines(string) method and combine the output like

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

You can try this for combining names:

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

Or can use 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM