简体   繁体   English

C#将.csv文件从本地计算机复制到远程Postresql服务器

[英]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. 我正在C#程序中创建.csv文件,我想通过COPY命令将它们上传到postgres表中。 COPY wants the files to be on database server but I have them localy. COPY希望文件位于数据库服务器上,但我在本地使用。 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方法复制它:

File.Copy(sourceFile, destFile);

Source : File.Copy on MSDN 来源: MSDN上的File.Copy

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 . 例如,您可以通过FTP上传文件或通过HTTPWeb表单提交文件。 Or you can attach remote filesystem as external drive to your local machine and just copy that. 或者,您可以将远程文件系统作为外部驱动器附加到本地计算机,然后将其复制。

Also, there are many utilities like SqlBulkCopy . 此外,还有许多实用程序,例如SqlBulkCopy It allows you not to upload your file but remotely insert multiple rows from DataTable . 它允许您不上传文件,而是从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... 好吧,我发现了一种非常聪明的方法:)我在查询中使用STDIN,之后我就在流式传输文件的内容...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM