[Solved] Find whitespace and add line break on a text file C#


Its not quite clear what you are asking, in case you want the output to be in file aswell, you could try this FormatFile Function. Its reads all lines from file at once though, so be careful with bigger files. It loops through all lines then it splits that line on a whitespace character. Depending on what you want the output to look like you can alter the “if” statements. finally flush the StreamWriter down to the Filestream. All closing and disposing is done by the using statement.

static void Main(string[] args)
{
    FormatFile(@"c:\test.txt");
}

public static void FormatFile(string pathToFile)
{
    string[] lines = File.ReadAllLines(pathToFile);
    using (FileStream fs = new FileStream(pathToFile, FileMode.OpenOrCreate))
    using (StreamWriter sw = new StreamWriter(fs))
    {
        foreach( string line in lines)
        {
            if (String.IsNullOrWhiteSpace(line))
                continue;

            string[] parts = line.Split(' ');

            for (int i = 0; i < parts.Length; i++)
            {
                string part = parts[i].Trim();
                if (!String.IsNullOrWhiteSpace(part))
                {
                    sw.WriteLine(part);
                }
                else //if( ... )
                {
                    sw.WriteLine("-");
                }
                //else if( ...)
                //{
                //    sw.WriteLine("KPC1");
                //}
                //else
                //{
                //
                //}
            }   
        }
        sw.Flush(); 
    }
}

solved Find whitespace and add line break on a text file C#