0

I've tried a few different methods and none of them work correctly so I'm just looking for someone to straight out show me how to do it . I want my application to read in a file based on an OpenFileDialog.

When the file is read in I want to go through it and and run this function which uses Linq to insert the data into my DB.

 objSqlCommands.sqlCommandInsertorUpdate

However I want to go through the string , counting the number of ","'s found . when the number reaches four I want to only take the characters encountered until the next "," and do this until the end of the file .. can someone show me how to do this ?

Based on the answers given here my code now looks like this

string fileText = File.ReadAllText(ofd.FileName).Replace(Environment.NewLine, ",");

               int counter = 0;
               int idx = 0;
               List<string> foo = new List<string>();

               foreach (char c in fileText.ToArray())
               {
                   idx++;
                   if (c == ',')
                   {
                       counter++;
                   }
                   if (counter == 4)
                   {
                       string x = fileText.Substring(idx);
                       foo.Add(fileText.Substring(idx, x.IndexOf(',')));
                       counter = 0;
                   }
               }

               foreach (string s in foo)
               {
                   objSqlCommands.sqlCommandInsertorUpdate("INSERT", s);//laClient[0]);
               }

However I am getting an "length cannot be less than 0" error on the foo.add function call , any ideas ?

user2546071
  • 51
  • 1
  • 10
  • I think you should provide some example: `input` and `output`, also more info on your function: `its signature including return type and parameters`. – King King Aug 06 '13 at 08:10
  • Show us what you have tried. To get you started have a look at `File.ReadAllLines()` and `String.Split()` – Ash Burlaczenko Aug 06 '13 at 08:10
  • @KinngKing , the input is just a normal txt file which is then read into a list of strings. after that it should just be a simple string manipulation however I just can't get it to work so I'm open to all ideas – user2546071 Aug 06 '13 at 08:11
  • @user2546071 What have you tried? – DGibbs Aug 06 '13 at 08:13
  • @DGibbs ,I've been tryin to use substring as well as for loops – user2546071 Aug 06 '13 at 08:14
  • @user2546071 Can you post it? We might be able to see where you've gone wrong – DGibbs Aug 06 '13 at 08:14
  • @user2546071 - Posting your code, even if it doesn't work, will help us help you. You might be close to the solution and just need to tweak a thing or two. – Tim Aug 06 '13 at 08:15
  • @Tim , there is no code at the moment I've just scrapped it after the nth attempt failed .. All I was using was a for loop , an int counter (to count the commas) and then I had it so once the 4th was hit it would take the chars encountered until the 5th was hit – user2546071 Aug 06 '13 at 08:16
  • is this data CSV? Should you be worried about escaping? – Jodrell Aug 06 '13 at 08:16
  • Is `,` the seperator or is it `","`? – Jodrell Aug 06 '13 at 08:17
  • @Jodrell , the file being read in is csv yeah , once its read in i'm doing the manipulation as a string though so I'm not sure if it being csv matters , could be wrong though – user2546071 Aug 06 '13 at 08:18
  • Take a look at this answer. http://stackoverflow.com/a/3508572/659190 – Jodrell Aug 06 '13 at 09:11

4 Answers4

1

File.ReadAllText reads a text file to a string and Split turns that string into an array seperated at the commas:

File.ReadAllText(OpenDialog.FileName).Split(',')[4]

If you have more than one line use:

File.ReadAllLines(OpenDialog.FileName).Select(l => l.Split(',')[4])

This gives an IEnumerable<string> where each string contains the wanted part from one line of the file

Raidri
  • 17,258
  • 9
  • 62
  • 65
  • this seems to work , however it wont go past the first line in the txt file , my code now looks like this foreach (string[] laClient in lsClientList) { string records = File.ReadAllText(ofd.FileName).Split(',')[4]; // read the file completely line by line – user2546071 Aug 06 '13 at 08:28
1

A Somewhat hacky example. You would pass this the entire text from your file as a single string.

string str = "1,2,3,4,i am some text,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();

foreach (char c in str.ToArray())
{
     idx++;
     if (c == ',')
     {
          counter++;
     }
     if (counter == 4)
     {
          string x = str.Substring(idx);
          foo.Add(str.Substring(idx, x.IndexOf(',')));
          counter = 0;
     }
}

foreach(string s in foo)
{
     Console.WriteLine(s);
}
Console.Read();

Prints:

  • i am some text
  • 9
  • 13
  • 17
DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • 1
    doesnt matter if its hacky lol just want it finished at this stage , thanks though this looks fine I'll be able to use this !! – user2546071 Aug 06 '13 at 08:39
1

As Raidri indicates in his answer, String.Split is definitely your friend. To catch every fifth word, you could try something like this (not tested):

string fileText = File.ReadAllText(OpenDialog.FileName).Replace(Environment.NewLine, ",");

string words[] = fileText.Split(',');

List<string> everFifthWord = new List<string>();

for (int i = 4; i <= words.Length - 1, i + 5)
{
    everyFifthWord.Add(words[i]);
}

The above code reads the selected file from the OpenFileDialog, then replaces every newline with a ",". Then it splits the string on ",", and starting with the fifth word takes every fifth word in the string and adds it to the list.

Tim
  • 28,212
  • 8
  • 63
  • 76
0

It's not clear to me if you're after every fifth piece of text between the commas or if there are multiple lines and you want only the fifth piece of text on each line. So I've done both.

Every fifth piece of text:

var text = "1,2,3,4,i am some text,6,7,8,9"
    + ",10,11,12,13,14,15,16,17,18,19,20";

var everyFifth =
    text
        .Split(',')
        .Where((x, n) => n % 5 == 4);

everyFifth

Only the fifth piece of text on each line:

var lines = new []
{
    "1,2,3,4,i am some text,6,7",
    "8,9,10,11,12,13,14,15",
    "16,17,18,19,20",
};

var fifthOnEachLine =
    lines
        .Select(x => x.Split(',')[4]);

fifthOnEachLine

Enigmativity
  • 113,464
  • 11
  • 89
  • 172