c# copy 服务器上面的文件到本机,C#将.csv文件从本地计算机复制到远程Postresql服务器...

本文讨论了如何在C#程序中通过COPY命令将本地CSV文件上传到PostgreSQL数据库。虽然COPY命令通常要求文件位于数据库服务器上,但作者分享了通过文件流和Npgsql库实现从本地文件系统的数据流上传到数据库的方法,以及使用FTP、HTTP等其他远程文件上传选项。
摘要由CSDN通过智能技术生成

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?

Talk1:

psql \copy lets you upload from client to server.

Solutions1

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

File.Copy(sourceFile, destFile);

Talk1:

Well it looks like your question is more a postgresql than a C# question then.

Solutions2

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.

Solutions3

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();

Talk1:

I get serializer.ToStream is not set to an instance of an object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值