如何将txt或csv文件上传到windows表单c#

时间:2015-09-08 06:08:51

标签: c# file-upload

我想通过c#中的windows窗体上传txt或csv文件,并希望将数据导入数据库(sql server)。我怎样才能做到这一点?我面临两个问题: -

  1. 我没有任何文件上传工具,只有图片上传工具。

  2. 如果以某种方式我已经设法进行文件上传,我怎样才能将数据从txt文件导入到sql server数据库?

  3. 如果有人可以通过c#代码解决方案提供帮助,对我来说会很好并且有帮助吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试以下内容:

private void buttonGetFile_Click(object sender, EventArgs e)
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "Text files | *.txt"; // file types, that will be allowed to upload
    dialog.Multiselect = false; // allow/deny user to upload more than one file at a time
    if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK
    {
        String path = dialog.FileName; // get name of file
        using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
        {
            // reader will be having all data
        }
    }
}