1

I'm trying to generate Item IDs using StreamReader on my .CSV file (It has to be a .csv file). The Item ID should start at 1000 and go up (1001, 1002, etc.)

Right now, if the user presses "Generate ID", it will search the entire file for the value "1000", if it doesn't exist, it will write "1000" in the textbox.

Here's what I need help with: If the file contains "1000", I want it to read the LAST line, increase it by 1, then write the value in the textbox.. So, if my last value is 1005 in the .csv file, I want it to write 1006 in the textbox.

    private void GenerateID_Click(object sender, EventArgs e)
    {
        try
        {
            string searchString = "1000";
            using (StreamReader sr = new StreamReader("file.csv"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (line.Contains(searchString))
                    {
                        /* If file contains 1000, read the LAST line
                         * (Whatever number that may be: 1001, 1002, 1003, etc.)
                         * and increase that number by 1, then write to textbox. */
                    }
                    else
                    {
                        invItemIDField.Text = Convert.ToString("1000");
                    }
                }
            }
        }
        catch (Exception)
        {
            MessageBox.Show("The file could not be read");
        }
    }
HNVDB
  • 39
  • 1
  • 7

2 Answers2

3

I suggest you use FileHelpers. It's the most suitable library for reading CSV files.

To install this, you need to install first NuGet. Once installed, go to Tools > Library Package Manager > Package Manager Console:

NuGet Package Manager

Then, type in: Install-Package Filehelpers

You're good to go!

Import FileHelpers to your code

using FileHelpers;

Create a class that describes the structure of your CSV:

DelimitedRecord("'")]
public class MyCsv
{
    public int Column1; // Your ID column
    public string SomeOtherColumn; 
}

Create a List<MyCsv>:

List<MyCsv> myList;

Then, to load your CSV:

FileHelperEngine<MyCsv> engine = new FileHelperEngine<MyCsv>();
myList = new List<MyCsv>(engine.ReadFile("my.csv")); // replace with your filename or variable containing the filename

You can now read your CSV by accessing the list myList:

foreach(MyCsv line in myList) {
    // Do something;
}

Each object inside that list corresponds to each row in your CSV. In order to access the first column of a row (given the foreach loop above):

line.Column1

So, if you need to compare values, you can either use LINQ or do the traditional loop-search:

foreach(MyCsv line in myList) {
    if (txtId.Text == line.Column1.ToString()) {
        found = true;
        break;
    }
}

Then, to get the id of the last row:

myList.[myList.Count - 1].Column1

You can do the rest. Cheers!

Ruel
  • 15,438
  • 7
  • 38
  • 49
2

Here's my go at it, it's slighlty different from yours, but it works. Granted there are things you must consider, such as are the elements surrounded in quotes, are the line breaks \r\n, and the like:

    int TextBoxValue = 1000;
    var reader = new StreamReader(File.OpenRead(@"C:\Users\J\Desktop\New Text Document (4).txt"));
    var contents = reader.ReadToEnd().Split(new string[] {"\r\n"}, StringSplitOptions.None);

    var iValueExists = (from String sLine in contents
                        where sLine.Contains("1000")
                        select sLine).Count();
    if (iValueExists > 0)
    {
        TextBoxValue = int.Parse(contents.Last().Split(new string[] {","}, StringSplitOptions.None).First()) + 1;
    }

    invItemIDField.Text = TextBoxValue;
    reader.Close();

enter image description here

KreepN
  • 8,528
  • 1
  • 40
  • 58
  • Hmm.. my rep is not high enough to chat, I can see your writing but cannot reply (required 20). – HNVDB Dec 10 '12 at 01:34