0

The program i got is able to load CSV and Excel files in to a datagridview. This works perfectly fine except the CSV files retain old data.

For example, the CSV file has 30 values. i load the data in to the datagridview and it works fine. I close the application and i then edit the CSV file removing 26 of the rows. The next time i open the application and load the file it still get's the version with 30 values even tho that file no longer exists.

To be clear, i open and edit the file in Notepad and it works as intended, but even after editing it in notepad my Winform application seems to load the previous version. Even if i rename the file it still takes the data that should no longer exist. Even after completely restarting the PC the file still retains data that should not exist. BUT! If i move the file to a different folder (add new folder and just throw it in there) it does load the new data...

EDIT: It seems that it is actually loading all CSV files in the folder. (including older versions)

what could cause this problem? Seeing the Excel files are not experiencing this problem.

The code used:

    private void OpenExcel()
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog
        {
            InitialDirectory = @"C:\",
            Title = "Browse Text Files",

            CheckFileExists = true,
            CheckPathExists = true,

            DefaultExt = "txt",
            FilterIndex = 2,
            RestoreDirectory = true,

            ReadOnlyChecked = true,
            ShowReadOnly = true,
            Filter = "Excel Worksheets|*.csv"
        };

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            FileLocation  = openFileDialog1.FileName;                
            GetExcelSheetNames(openFileDialog1.FileName);

            MyConnection = new OleDbConnection(connString);

            MyCommand = new OleDbDataAdapter("select * from [" + SheetName + "]", MyConnection);
            MyCommand.TableMappings.Add("Table", "TestTable");
            Datatable_Temp = new DataTable();
            MyCommand.Fill(Datatable_Temp);
            MyConnection.Close();              
        }
        else
        {
            Canceled = true;
        }            
    }

    private string GetExcelSheetNames(string excelFile)
    {
        OleDbConnection objConn = null;
        DataTable dt = null;
        string CSVOrNot = excelFile.Substring(excelFile.Length - 3);    

        try
        {
            // Connection String.
            if (CSVOrNot == "csv")
            {
                connString = string.Format(@"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""", Path.GetDirectoryName(excelFile));
            }
            else
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + excelFile + ";Extended Properties=Excel 12.0;";
            }
            // Create connection object by using the preceding connection string.
            objConn = new OleDbConnection(connString);
            // Open connection with the database.
            objConn.Open();
            // Get the data table containg the schema guid.
            dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            if (dt == null)
            {
                MessageBox.Show("No Data Found");
                return null;
            }
            SheetName = dt.Rows[0]["TABLE_NAME"].ToString();

            return SheetName;
        }
        catch
        {
            return null;
        }
        finally
        {
            // Clean up.
            if (objConn != null)
            {
                objConn.Close();
                objConn.Dispose();
            }
            if (dt != null)
            {
                dt.Dispose();
            }
        }
    }
A.bakker
  • 221
  • 1
  • 9
  • Did your changes to CSV file really get saved? Are you sure you're loading the changed file? – Markus Deibel Nov 26 '19 at 14:48
  • 2
    Make sure application is not saving a xlsx instead of a csv. Where is the SAVE? You are using oledb and must write data back with an Update or Insert. – jdweng Nov 26 '19 at 15:05
  • @MarkusDeibel i did save it as a CSV file using notepad. If i open the file in notepad or Excel the file has done what it has supposed to but for some reason my Winforms keep loading the file that doesn't exist anymore. Like if it's in some kind of cache. – A.bakker Nov 27 '19 at 06:15
  • @jdweng i actually alter the file in Notepad, not in my program. See my other comment for details. – A.bakker Nov 27 '19 at 06:16
  • Without a good [mcve] that reliably reproduces the problem, it'll be hard if not impossible to provide a good answer. That said, based on the way your code works, using Excel to parse the CSV, I'll bet that after you close your program if you check Task Manager you'll find an Excel process still running, and when you restart your program, it probably winds up reconnected with that process. – Peter Duniho Nov 27 '19 at 06:40
  • @PeterDuniho nope the connection is closed (and Excel no longer appears in the task manager). And the code shows is the entirety of the code used (besides the button click event that starts it and the datagrid filling). I just edited the file and MOVED it to a other folder. made a copy of the file and placed it at the original location. The original one that got moved shows the correct data. the copy placed at the original location shows the old data... i am honestly baffled :| – A.bakker Nov 27 '19 at 06:58
  • 1
    _"the code showsn is the entirety of the code used"_ -- it's certainly not. At the very least, it's missing the _declarations_ of various variables used in the program. And it requires external setup, such as the CSV file itself and of course the Excel installation. If you can't reproduce this without Excel, then it's really more of an Excel user question than a programming question. – Peter Duniho Nov 27 '19 at 07:00
  • @PeterDuniho it can function without Excel as it can be opened in any text editor. And i honestly starting tot think it's more of a setting issue then a coding issue. as if some kind of cache is being used. – A.bakker Nov 27 '19 at 07:14
  • Your code uses Excel. I'm saying that if you can't write an example that simply reads the file directly, instead of going through Excel's data adapter, then this is just an Excel user issue. Yes, there's obviously some cache involved. But the usual suspects -- drive, file system, CPU, etc. -- all are heavily tested and aren't going to return stale data. You must have some less-robust cache that is specific to your system config which is causing the issue. – Peter Duniho Nov 27 '19 at 07:17
  • 1
    @A.bakker: ignoring the request to post the **complete** code doesn't make it easy for us to help you. – Doc Brown Nov 27 '19 at 07:18
  • @PeterDuniho: as far as I can see, the code uses the Jet Engine (which was part of MS Access, older versions became part of Windows) and not Excel - there will no Excel process be started in the background – Doc Brown Nov 27 '19 at 07:25
  • @Doc: maybe, I'm not that familiar with how those components work. The connection string still carries a reference to the Excel version, but I suppose that may or may not actually cause the Jet DLL to load Excel. In any case, no matter what, I don't see anything here that is an actual _programming_ question that would make this post on-topic for Stack Overflow. – Peter Duniho Nov 27 '19 at 07:28
  • @PeterDuniho: no, the Jet Engine does not "load Excel", it has some (restricted) capabilities to read Excel files (as well as Access files, and probably CSV files) directly. We used these techniques for reading Excel files 10 years ago, but I never tried it for CSV files directly. If it turns out to be a caching problem with the Jet Engine, it looks very much like a programming problem to me (but I am not willing to debug here anything if the OP refuses to post the full code so I could compile and run it by myself). – Doc Brown Nov 27 '19 at 07:34
  • @PeterDuniho solved it. – A.bakker Nov 27 '19 at 08:00
  • The OP is using oledb and only read data using a select. To save changes in oledb you either have to do an INSERT or UPDATE. – jdweng Nov 27 '19 at 09:47
  • @jdweng as stated before, it is only for VIEWING the data. The changing of the data is done outside the program in regular notepad. – A.bakker Nov 27 '19 at 10:22

1 Answers1

1

i Found the issue, it was different then i thought. Seeing older versions of the file were also in the folder i didn't notice that it wasn't taking an older version of itself but it was simply merging all CSV files in to the output.

I searched for this instead and found the following post: c# reading csv file gives not a valid path

i added an if clause to see if the file is a csv file and then use the following: Because the difference between opening an Excel or a CSV file is is that the Excel file asked for path and file name while CSV only wants the path and later on a query to select the file...a bit odd but ok.

MyCommand = new OleDbDataAdapter("SELECT * FROM [" + Path.GetFileName(openFileDialog1.FileName) + "]", MyConnection);
A.bakker
  • 221
  • 1
  • 9