简体   繁体   中英

Creating a new txt file from an already existing one

I am trying to create a new text file from an already existing one. Right now, I can display the entire text file (test.txt). The file displays a ton of information, but I am concerned displaying the following, which happen to be the first 6 columns of the txt file. Here they are:

  • Version control
  • Plan Number
  • Acct Number
  • Country
  • Invoice Date
  • Invoice Number

This is how I have my Program.cs file set up:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace TextFileDataAccessDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"C:\MyData\test.txt";

            List<string> lines = File.ReadAllLines(filePath).ToList();

            //This loops over every line in the list of strings. 
            foreach (string line in lines)
            {
                Console.WriteLine(line);
            }



            File.WriteAllLines(filePath, lines);



            Console.ReadLine();
        }
    }
}

How can I parse through the entire file, using streamreader and streamwriter, and create a new file that will ''spit out'' the data I want, which is what I listed above. I would like the new data file to start with the Invoice Number, which starts at 40 characters and is 15 characters long (40,15). Any help or leads are very appreciated. I have been stuck for hours and do not know where to begin.

First of all, there is no such thing as a text file with columns. A text file contains only characters and contains no structuring information.

So in your file, there is probably some character that is used as a separator, most commonly used is the semi-colon ;

You made the easy part: opening the file, reading all the line then writing in the new file.

What is left would be inside your foreach loop (assuming your file is using a separator for the columns):

  • Split the string into an array using this separator
  • Put in another string the parts of the array you want to keep
  • Write this line into your new file

You could process the file line by line and you shouldn't need streams.

It could be as simple as

var newLines = lines.Select( l => l.Substring(40));

If you need process the input files (change order, etc.) then the following tools should do bulk of the work:

  • string.Split
  • string.Substring - the 2nd param is length so line.Substring(40,15) is the invoice number.

Good luck!

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