简体   繁体   中英

Save Array to text in C#

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

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.

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