Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Split text file by Fixed Length

Split text file by Fixed Length

Scheduled Pinned Locked Moved C#
tutorial
20 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y yueru

    Who knows How to Split data by Fixed length

    N Offline
    N Offline
    N a v a n e e t h
    wrote on last edited by
    #3

    I know ;P

    Navaneeth How to use google | Ask smart questions

    Y 1 Reply Last reply
    0
    • Y yueru

      Who knows How to Split data by Fixed length

      M Offline
      M Offline
      Mycroft Holmes
      wrote on last edited by
      #4

      Me, me, me, I do!

      Never underestimate the power of human stupidity RAH

      1 Reply Last reply
      0
      • M musefan

        what exactly do you mean?

        Life goes very fast. Tomorrow, today is already yesterday.

        Y Offline
        Y Offline
        yueru
        wrote on last edited by
        #5

        I mean if I have text file like this

        ==lo12365=12/08/05 12.30 lo op
        ==lo12589=13/08/04 12.15 li oo
        ==lo89099=18/05/09 12.10 io io

        How to read in C# Someone said I should use split and Format = fixed Length But I don't know how ????

        M 1 Reply Last reply
        0
        • N N a v a n e e t h

          I know ;P

          Navaneeth How to use google | Ask smart questions

          Y Offline
          Y Offline
          yueru
          wrote on last edited by
          #6

          So how to ???

          Y 1 Reply Last reply
          0
          • Y yueru

            I mean if I have text file like this

            ==lo12365=12/08/05 12.30 lo op
            ==lo12589=13/08/04 12.15 li oo
            ==lo89099=18/05/09 12.10 io io

            How to read in C# Someone said I should use split and Format = fixed Length But I don't know how ????

            M Offline
            M Offline
            musefan
            wrote on last edited by
            #7

            if you want to read a file you a System.IO.StreamReader which has functions such as ReadLine(); Each time you call ReadLine(); it will return a string of the next line in the file, until null (end of file). You can then do what you want with that string. If you need dates and times seperate you will prob want to use String.Split() method.

            Life goes very fast. Tomorrow, today is already yesterday.

            Y 1 Reply Last reply
            0
            • Y yueru

              Who knows How to Split data by Fixed length

              V Offline
              V Offline
              Vasudevan Deepak Kumar
              wrote on last edited by
              #8

              Quoting Sean Hederman from http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/b0d4cba1-471a-4260-94c1-fddd4244fa23/[^]

              string sourceFileName = @"C:\VS2005 SP1.exe";

              string destFileLocation = @"C:\";

              int index = 0;

              long maxFileSize = 52428800;

              byte[] buffer = new byte[65536];

              using (Stream source = File.OpenRead(sourceFileName))

              {

              while (source.Position < source.Length)
              
              {
              
                  index++;
              
              
              
                  // Create a new sub File, and read into t
              
                  string newFileName = Path.Combine(destFileLocation, Path.GetFileNameWithoutExtension(sourceFileName));
              
                  newFileName += index.ToString() + Path.GetExtension(sourceFileName);
              
                  using (Stream destination = File.OpenWrite(newFileName))
              
                  {
              
                      while (destination.Position < maxFileSize)
              
                      {
              
                          // Work out how many bytes to read
              
                          int bytes = source.Read(buffer, 0, (int) Math.Min(maxFileSize, buffer.Length));
              
                          destination.Write(buffer, 0, bytes);
              
              
              
                          // Are we at the end of the file?
              
                          if (bytes < Math.Min(maxFileSize, buffer.Length))
              
                          {
              
                              break;
              
                          }
              
                      }
              
                  }
              
              }
              

              }

              Vasudevan Deepak Kumar Personal Homepage
              Tech Gossips
              The woods are lovely, dark and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep!

              Y 1 Reply Last reply
              0
              • M musefan

                if you want to read a file you a System.IO.StreamReader which has functions such as ReadLine(); Each time you call ReadLine(); it will return a string of the next line in the file, until null (end of file). You can then do what you want with that string. If you need dates and times seperate you will prob want to use String.Split() method.

                Life goes very fast. Tomorrow, today is already yesterday.

                Y Offline
                Y Offline
                yueru
                wrote on last edited by
                #9

                Yeppp I've knowed how to read I use

                using System.IO;
                namespace WindowsApplication23
                {
                public partial class Form1 : Form
                {
                OpenFileDialog o;
                FileInfo info;
                public Form1()
                {
                InitializeComponent();
                }
                private void button1_Click(object sender, EventArgs e)
                {
                o = new OpenFileDialog();
                if (o.ShowDialog() == DialogResult.OK)
                {
                info = new FileInfo(o.FileName);
                label1.Text = info.ToString();
                }
                }
                private void button2_Click(object sender, EventArgs e)
                {
                StreamReader reader = info.OpenText();
                textBox1.Text = reader.ReadToEnd().ToString();
                reader.Close();
                }
                }
                }

                but it read all of my file I just want it from ==lo12365=12/08/05 12.30 lo op ==lo12589=13/08/04 12.15 li oo ==lo89099=18/05/09 12.10 io io tobe lo12365 12/08/05 12.30 lo op lo12589 13/08/04 12.15 li oo lo89099 18/05/09 12.10 io io and insert it to my table thx in advance

                M 1 Reply Last reply
                0
                • Y yueru

                  Yeppp I've knowed how to read I use

                  using System.IO;
                  namespace WindowsApplication23
                  {
                  public partial class Form1 : Form
                  {
                  OpenFileDialog o;
                  FileInfo info;
                  public Form1()
                  {
                  InitializeComponent();
                  }
                  private void button1_Click(object sender, EventArgs e)
                  {
                  o = new OpenFileDialog();
                  if (o.ShowDialog() == DialogResult.OK)
                  {
                  info = new FileInfo(o.FileName);
                  label1.Text = info.ToString();
                  }
                  }
                  private void button2_Click(object sender, EventArgs e)
                  {
                  StreamReader reader = info.OpenText();
                  textBox1.Text = reader.ReadToEnd().ToString();
                  reader.Close();
                  }
                  }
                  }

                  but it read all of my file I just want it from ==lo12365=12/08/05 12.30 lo op ==lo12589=13/08/04 12.15 li oo ==lo89099=18/05/09 12.10 io io tobe lo12365 12/08/05 12.30 lo op lo12589 13/08/04 12.15 li oo lo89099 18/05/09 12.10 io io and insert it to my table thx in advance

                  M Offline
                  M Offline
                  musefan
                  wrote on last edited by
                  #10

                  Well as i suggested use ReadLine() you are using ReadToEnd() which is not what you want. in you button2_Click...

                  StreamReader reader = new StreamReader(info.Filname);

                  string line = reader.ReadLine();
                  while(line!= null)
                  {
                  string newLine = line.Replace("=", " ");
                  string[] vals = newLine.Split(' ');//use this if you need values seperate for table
                  //do something like add newLine to table, or add the string in the vals array
                  line = reader.ReadLine();
                  }

                  reader.Close();

                  Life goes very fast. Tomorrow, today is already yesterday.

                  Y 1 Reply Last reply
                  0
                  • M musefan

                    Well as i suggested use ReadLine() you are using ReadToEnd() which is not what you want. in you button2_Click...

                    StreamReader reader = new StreamReader(info.Filname);

                    string line = reader.ReadLine();
                    while(line!= null)
                    {
                    string newLine = line.Replace("=", " ");
                    string[] vals = newLine.Split(' ');//use this if you need values seperate for table
                    //do something like add newLine to table, or add the string in the vals array
                    line = reader.ReadLine();
                    }

                    reader.Close();

                    Life goes very fast. Tomorrow, today is already yesterday.

                    Y Offline
                    Y Offline
                    yueru
                    wrote on last edited by
                    #11

                    It has error on

                    StreamReader reader = new StreamReader(info.Filname);

                    can I change it to b

                    StreamReader reader = new StreamReader(o.FileName);

                    and it can't run on Button2 I don't know why

                    M 1 Reply Last reply
                    0
                    • V Vasudevan Deepak Kumar

                      Quoting Sean Hederman from http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/b0d4cba1-471a-4260-94c1-fddd4244fa23/[^]

                      string sourceFileName = @"C:\VS2005 SP1.exe";

                      string destFileLocation = @"C:\";

                      int index = 0;

                      long maxFileSize = 52428800;

                      byte[] buffer = new byte[65536];

                      using (Stream source = File.OpenRead(sourceFileName))

                      {

                      while (source.Position < source.Length)
                      
                      {
                      
                          index++;
                      
                      
                      
                          // Create a new sub File, and read into t
                      
                          string newFileName = Path.Combine(destFileLocation, Path.GetFileNameWithoutExtension(sourceFileName));
                      
                          newFileName += index.ToString() + Path.GetExtension(sourceFileName);
                      
                          using (Stream destination = File.OpenWrite(newFileName))
                      
                          {
                      
                              while (destination.Position < maxFileSize)
                      
                              {
                      
                                  // Work out how many bytes to read
                      
                                  int bytes = source.Read(buffer, 0, (int) Math.Min(maxFileSize, buffer.Length));
                      
                                  destination.Write(buffer, 0, bytes);
                      
                      
                      
                                  // Are we at the end of the file?
                      
                                  if (bytes < Math.Min(maxFileSize, buffer.Length))
                      
                                  {
                      
                                      break;
                      
                                  }
                      
                              }
                      
                          }
                      
                      }
                      

                      }

                      Vasudevan Deepak Kumar Personal Homepage
                      Tech Gossips
                      The woods are lovely, dark and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep!

                      Y Offline
                      Y Offline
                      yueru
                      wrote on last edited by
                      #12

                      Thank you for a example for multiple textfile So do u have example about split ? Thank you in advance

                      1 Reply Last reply
                      0
                      • Y yueru

                        It has error on

                        StreamReader reader = new StreamReader(info.Filname);

                        can I change it to b

                        StreamReader reader = new StreamReader(o.FileName);

                        and it can't run on Button2 I don't know why

                        M Offline
                        M Offline
                        musefan
                        wrote on last edited by
                        #13

                        yes you can change it to that. The parameter is just the full path of the file. And why cant it work it buttonClick? you get error message? You can put the code anywhere. you decide where is best for you

                        Life goes very fast. Tomorrow, today is already yesterday.

                        Y 1 Reply Last reply
                        0
                        • M musefan

                          yes you can change it to that. The parameter is just the full path of the file. And why cant it work it buttonClick? you get error message? You can put the code anywhere. you decide where is best for you

                          Life goes very fast. Tomorrow, today is already yesterday.

                          Y Offline
                          Y Offline
                          yueru
                          wrote on last edited by
                          #14

                          I don't know why I add

                          string line = reader.ReadLine();
                          while (line != null)
                          {
                          string newLine = line.Replace("=", " ");
                          string[] vals = newLine.Split(' ');//use this if you need values seperate for table
                          //do something like add newLine to table, or add the string in the vals array
                          line = reader.ReadLine();
                          }
                          //I add this
                          textBox4.Text = reader.ReadLine();
                          reader.Close();

                          and then when I click in button 2 it 's nothing but button 1 can use Thank in advance

                          M OriginalGriffO 2 Replies Last reply
                          0
                          • Y yueru

                            I don't know why I add

                            string line = reader.ReadLine();
                            while (line != null)
                            {
                            string newLine = line.Replace("=", " ");
                            string[] vals = newLine.Split(' ');//use this if you need values seperate for table
                            //do something like add newLine to table, or add the string in the vals array
                            line = reader.ReadLine();
                            }
                            //I add this
                            textBox4.Text = reader.ReadLine();
                            reader.Close();

                            and then when I click in button 2 it 's nothing but button 1 can use Thank in advance

                            M Offline
                            M Offline
                            musefan
                            wrote on last edited by
                            #15

                            well i would guess you problem is you have not assigned the event handler to button2. Go in design view, select button2, go to the events tab on the right and make sure 'Click' has been set to the handler.

                            Life goes very fast. Tomorrow, today is already yesterday.

                            Y 1 Reply Last reply
                            0
                            • M musefan

                              well i would guess you problem is you have not assigned the event handler to button2. Go in design view, select button2, go to the events tab on the right and make sure 'Click' has been set to the handler.

                              Life goes very fast. Tomorrow, today is already yesterday.

                              Y Offline
                              Y Offline
                              yueru
                              wrote on last edited by
                              #16

                              Yepp I've done it but It still can't run The first I assign

                              textBox4.Text = reader.ReadLine.ToString();

                              but it said I used wrong method so I change it to be

                              textBox4.Text = reader.ReadLine.();

                              It's no error but can't use I don't know why TwT Message when it error http://www.uppicth.com/show.php?filex=e5d4b8cd0fec144f140ded8bcbcfe23a.JPG[^]

                              modified on Thursday, April 30, 2009 6:15 AM

                              M 1 Reply Last reply
                              0
                              • Y yueru

                                Yepp I've done it but It still can't run The first I assign

                                textBox4.Text = reader.ReadLine.ToString();

                                but it said I used wrong method so I change it to be

                                textBox4.Text = reader.ReadLine.();

                                It's no error but can't use I don't know why TwT Message when it error http://www.uppicth.com/show.php?filex=e5d4b8cd0fec144f140ded8bcbcfe23a.JPG[^]

                                modified on Thursday, April 30, 2009 6:15 AM

                                M Offline
                                M Offline
                                musefan
                                wrote on last edited by
                                #17

                                should be textBox4.Text = reader.ReadLine(); where are you using that thou? are you sure your not reading a null value?

                                Life goes very fast. Tomorrow, today is already yesterday.

                                1 Reply Last reply
                                0
                                • Y yueru

                                  I don't know why I add

                                  string line = reader.ReadLine();
                                  while (line != null)
                                  {
                                  string newLine = line.Replace("=", " ");
                                  string[] vals = newLine.Split(' ');//use this if you need values seperate for table
                                  //do something like add newLine to table, or add the string in the vals array
                                  line = reader.ReadLine();
                                  }
                                  //I add this
                                  textBox4.Text = reader.ReadLine();
                                  reader.Close();

                                  and then when I click in button 2 it 's nothing but button 1 can use Thank in advance

                                  OriginalGriffO Offline
                                  OriginalGriffO Offline
                                  OriginalGriff
                                  wrote on last edited by
                                  #18

                                  If you look closely at the code segement you posted:

                                  yueru wrote:

                                  string line = reader.ReadLine();
                                  while (line != null)
                                  {
                                  string newLine = line.Replace("=", " ");
                                  string[] vals = newLine.Split(' ');
                                  line = reader.ReadLine();
                                  }
                                  //I add this
                                  textBox4.Text = reader.ReadLine();
                                  reader.Close();

                                  The problem becomes obvious, no? When does it exit from the while loop? How much of the file is left to be read into textBox4? If you still can't see it, run it slowly through the debugger (sorry Luc) and it should be crystal clear. Before you ask, no I won't correct your code. This is a basic error and you will learn better finding it yourself - you have all the clues and tools you need.

                                  No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

                                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                                  1 Reply Last reply
                                  0
                                  • Y yueru

                                    Who knows How to Split data by Fixed length

                                    M Offline
                                    M Offline
                                    Mbah Dhaim
                                    wrote on last edited by
                                    #19

                                    I will try to resume all answers in the following steps 1. Open file that you want to parse 2. Use StreamReader to read the file 3. Read line using StreamReader.ReadLine(); 4. If Step 3 has data, continue to next step, other wise go to step 9 5. from result in above step replace all unnecessary characters with space, in your sample data replace "==" and '=' to space 6. split result from step 5 using method [yourstring].split in your sample use space as split character 7. post result from step 6 to database 8. repeat step 3 until 7 9. close your StreamReader 10. if there are errors occurred after you doing all steps, ask about them to this forum and read correlated documentations you need happy coding... :)

                                    dhaim ing ngarso sung tulodho, ing madyo mangun karso, tut wuri handayani. "Ki Hajar Dewantoro" in the front line gave a lead, in the middle line build goodwill, in the behind give power support

                                    1 Reply Last reply
                                    0
                                    • Y yueru

                                      So how to ???

                                      Y Offline
                                      Y Offline
                                      yueru
                                      wrote on last edited by
                                      #20

                                      Forget about Fixed length it's not my point NOw I 've got the code

                                      String inputfilename = "";
                                      private void Add(){

                                      StreamReader reader = new StreamReader(inputfilename);
                                      //MessageBox.Show(inputfilename);

                                              string line = reader.ReadLine();
                                      
                                              while (line != null)
                                              {
                                                  string Date = line.Substring(12, 8);
                                                  if (line.Substring(11, 1) == "=")
                                                  {
                                                      string Time = line.Substring(21, 5);
                                                      string Linein = line.Substring(27, 10);
                                                      string Lineout = line.Substring(38, 1);
                                                      
                                      
                                                      if ((string.Compare(Lineout, "0") > 0 || string.Compare(Lineout, "0") == 0) && (string.Compare(Lineout, "9") < 0 || string.Compare(Lineout, "9") == 0))
                                                      {
                                                          //int g = line.Length;
                                                          //string Number = line.Substring(40, g - 40);
                                                          string Number = line.Substring(40, 20);
                                                          string Status = line.Substring(61, 3);
                                                           string Duration = line.Substring(65, 9);
                                                            string Cost = line.Substring(75, 3);
                                                           string Detail = line.Substring(79, 2);
                                                           string Network = line.Substring(82, 8);
                                                         // trim whitespace from both ends of the elements
                                      
                                                          string txtSQLQuery = "insert into par values('" + Date + "','" + Time + "','" + Linein + "','" + Lineout + "','" + Number + "','" + Status + "','" + Duration + "','" + Cost + "','" + Detail + "','" + Network + "')";
                                                          ExecuteQuery(txtSQLQuery);
                                      
                                                          //MessageBox.Show(line);
                                      
                                      
                                                          textBox6.Text = textBox6.Text + "\\r\\n" + Date + " " + Time + " " + Linein + " " + Lineout + " " + Number + " ";
                                                      }
                                                      else
                                                      {
                                                          textBox5.Text = line + "\\r\\n" + textBox5.Text;
                                      
                                                      }
                                                  }
                                                  else
                                                  {
                                                      textBox5.Text = line + "\\r\\n" + textBox5.Text;
                                                  }
                                                  line = reader.ReadLine();
                                              }
                                      
                                              MessageBox.Show("End while loop");
                                          }
                                      

                                      thx for all comment +_! :)

                                      1 Reply Last reply
                                      0
                                      Reply
                                      • Reply as topic
                                      Log in to reply
                                      • Oldest to Newest
                                      • Newest to Oldest
                                      • Most Votes


                                      • Login

                                      • Don't have an account? Register

                                      • Login or register to search.
                                      • First post
                                        Last post
                                      0
                                      • Categories
                                      • Recent
                                      • Tags
                                      • Popular
                                      • World
                                      • Users
                                      • Groups