Search code examples
c#file-iostreamreader

Using C# how can I split a text file into multiple files


How can I split a text file that contains ASCII code SOH and ETX into multiple files?

For exmaple the text file I have named 001234.txt contains the following content:

SOH{ABCDXZY}ETX

SOH{ABCDXZY}ETX

SOH{ABCDXZY}ETX

I would like to split the single text file into multiple text files for each ASCII code that starts with SOH and ends with ETX.

The single text file name should be splitted into 101234.txt , 111234.txt..etc and each contains a single content that starts with SOH and ends with ETX.

I appreciate any help.

using System.IO; using System.Linq;

namespace ASCII_Split
{
    class Program
    {
        static void Main(string[] args)
        {
            var txt = "";
            const char soh = (char)1;
            const char eox = (char)3;
            var count = 1;
            var pathToFile = @"‪‪C:\Temp\00599060.txt";

            using (var sr = new StreamReader(pathToFile))
                txt = sr.ReadToEnd();

            while (txt.Contains(soh))
            {
                var outfil = Path.Combine(Path.GetDirectoryName(pathToFile), count.ToString("000"), "_fix.txt");
                var eInd = txt.IndexOf(eox);
                using (var sw = new StreamWriter(outfil, false))
                {
                    sw.Write(txt.Substring(1, eInd - 1));
                }
                txt = txt.Substring(eInd + 1);
                count++;
            }

        }
    }
}

Solution

  • Provided by SOH and ETX you mean the respective control characters, this here should get you on your way:

    var txt = "";
    const char soh = (char) 1;
    const char eox = (char) 3;
    var count = 1;
    var pathToFile = @"C:\00_Projects_temp\test.txt";
    
    using (var sr = new StreamReader(pathToFile))
        txt = sr.ReadToEnd();
    
    while (txt.Contains(soh))
    {
        var outfil = Path.Combine(Path.GetDirectoryName(pathToFile), count.ToString("000"), "_test.txt");
        var eInd = txt.IndexOf(eox);
        using (var sw = new StreamWriter(outfil, false))
        {
            sw.Write(txt.Substring(1, eInd - 1));
        }
        txt = txt.Substring(eInd + 1);
        count++;
    }