简体   繁体   中英

Accessing folder in console application

I'm trying to write a function to read csv contents into a datatable.
I'm getting an exception about the file path and wondering what it is that I'm doing wrong. All I did was create the console app and create a folder in the project called 'Data'.

public DataTable ReadCSV(string filename)
{
        DataTable dt = new DataTable();
        string sql = "SELECT * FROM " + filename;
        string path = "Data\\";
        string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";" + "Extended Properties='text;FMT=Delimited(;);HDR=YES'";
        OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connstring);
        System.Data.OleDb.OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);

        try
        {
            conn.Open();
            da.Fill(dt);
        }
        catch (Exception ex)
        {
            Console.WriteLine(filename + "not found");
        }

        finally
        {
            conn.Close();
        }
        return dt;
    }

}

My connection string in the Text visualizer when I run in debug mode:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data\\Positions.csv;Extended Properties='text;FMT=Delimited(;);HDR=YES'

I'm getting an exception

base {System.Data.Common.DbException} = {"'Data\\Positions.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides."}

Can anyone point me in the right direction? I have limited experience doing console apps so it's probably some formatting mistake that I've made. Thanks

and create a folder in the project called 'Data'.

That doesn't work. Your program is running in the bin\\Debug subdirectory of your project. It doesn't have a Data subdirectory. You'd have to use ..\\..\\Data\\Positions.csv to find that file.

Well, that would solve your problem right now but it isn't going to be useful once you copy your program to another machine. There won't be a ..\\..\\Data directory there. Think about ways that your user is going to tell you where the .csv file is located. A GUI with OpenFileDialog is the friendly way but not very compatible with a console app. The standard way for that is to pass command line arguments. Environment.CommandLine. Not very compatible with the typical user. You'll have to weigh these options by yourself.

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