Home > Software engineering >  Save Array to text in C#
Save Array to text in C#

Time:05-27

I've read a file from a text file and parsed the data I want, but I don't know how to save the parsed data in form to the file. Are you able to assist me? I've also included a snippet from the file. https://ibb.co/G5hTtky --> link for the image

public static void Main(string[] args)
    {
        StreamReader streamReader = File.OpenText(@"C:\Users\asr050322.txt");
        string text = streamReader.ReadToEnd();
        
        string[] linesArray = text.Split("BOH");
            for (int i = 0; i < linesArray.Length; i  )
            {
                if (linesArray[i].Substring(24, 5) == "UXOAP")
                {
                 File.WriteAllLines(@"C:\Users\HeUXOAP050322.txt", Array.ConvertAll(linesArray[i], x => x.ToString()));
                }

                if (linesArray[i].Substring(24, 5) == "UXOGS")
                {
                 File.WriteAllLines(@"C:\Users\UXOGS050322.txt", Array.ConvertAll(linesArray[i], x => x.ToString()));
                }
            }
    }

CodePudding user response:

There are several ways of doing that, you can check them here.

CodePudding user response:

File.WriteAllLines() will overwrite an existing file, so as you loop, you will only keep the latest data.

Use File.AppendText("path/to/file", linesArray[i]); This will create a file if it does not exist, then appends the data to the end of the existing file.

  • Related