简体   繁体   中英

C# copy .csv file from local machine to remote postresql server

I'm creating .csv files in my C# program and I want to upload them into a postgres table via COPY command. COPY wants the files to be on database server but I have them localy. Is there a way to upload them from the local machine?

If you can access to the server's hard drive, you can just copy it with File.Copy method :

File.Copy(sourceFile, destFile);

Source : File.Copy on MSDN

I think the best answer is: "Yes, there are many ways to upload file to remote server". You have really many options to do this. One that you may prefer depends on the way you communicate with your server.

For example, you can upload your file via FTP or submit it with web form through HTTP . Or you can attach remote filesystem as external drive to your local machine and just copy that.

Also, there are many utilities like SqlBulkCopy . It allows you not to upload your file but remotely insert multiple rows from DataTable .

Look at this post .

Well I found very clever way to do it :) I'm using STDIN in my query and after that I'm streaming the contents of the file...

        NpgsqlCommand dbcmd = dbcon.CreateCommand();
        string sql =
            "COPY table_name FROM STDIN;";
        dbcmd.CommandText = sql;
        serializer = new NpgsqlCopySerializer(dbcon);
        copyIn = new NpgsqlCopyIn(dbcmd, dbcon, serializer.ToStream);
        copyIn.Start();
        foreach(...){
            serializer.Add... 
            serializer.EndRow();
            serializer.Flush();
        }
        copyIn.End();
        serializer.Close();

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