0

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()));
                }
            }
    }
1
  • Are you looking for File.AppendAll(Lines|Text) ... Commented May 27, 2022 at 13:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, i did AppendAllText and it worked, and i have another question how do we prepend a string or a character to LinesArray[i]
as simple as string line = "prefix_string" + linesArray[i]. if you need to build a string with a lot of concats, replacing, etc, check out StringBuilder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.