代码之家  ›  专栏  ›  技术社区  ›  Eray Balkanli

通过C从CSV读取数据时“只能由另一个用户打开”#

  •  0
  • Eray Balkanli  · 技术社区  · 7 年前

    Microsoft Jet数据库引擎无法打开文件“”。它是 查看其数据。

    守则如下:

    private static string FileConnectionString(string filePath)
    {
        return string.Format(WebConfigurationManager.AppSettings["DataFileCSV"].ToString(), filePath);
    }
    

    string DataUploadFolder = WebConfigurationManager.AppSettings["DataFileUploadFolder"].ToString();
    string filePath = HttpContext.Current.Server.MapPath(DataUploadFolder);
    
    OleDbConnection fileConnection = new OleDbConnection(FileConnectionString(filePath));
    try
    {
        fileConnection.Open();
        string columnList = "Col1, Col2, Col3, Col4, Col5";
        DataTable fileDataTable = new DataTable();
        OleDbCommand command =  new OleDbCommand(string.Format("SELECT {0} FROM [{1}]",                                                                   
                                                 columnList,
                                                 FileUploadControl.FileName), 
                                    fileConnection);
        OleDbDataAdapter da = new OleDbDataAdapter(command);
        da.Fill(fileDataTable); //Exception occurs here !!
    }
    catch (Exception ex)
    {
    
    }
    finally
    {
        fileConnection.Close();
    }
    

    Web.config:

     <add key="DataFileCSV" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='text;HDR=Yes;FMT=Delimited';" />
    

    请注意,CSV文件未在任何位置打开。实际上没有打开任何文件,只有Visual Studio打开。我可以打开文件,更改并保存它。“Everyone”对该文件具有“完全控制”权限。

    我不明白为什么会发生错误,也找不到解决方法。看到许多页面出现此错误,但到目前为止还没有解决方案。任何帮助都将不胜感激。

    编辑:在aspx中,我使用: <asp:FileUpload ID="FileUploadControl" runat="server" Width="400px" />

    2 回复  |  直到 7 年前
        1
  •  0
  •   Eray Balkanli    7 年前

    需要遵循两个步骤:

    1-通过使用OleDBConnection,您无法读取原始文件,因为一旦打开文件连接,它就会开始使用上载的文件。这促使我们将文件复制到另一个临时位置。因此,在代码中添加检查行。

    FileUploadControl.SaveAs(filePath + fileName); //This is the line
    OleDbConnection fileConnection = new OleDbConnection(FileConnectionString(filePath, fileName));
    fileConnection.Open();
    

    它是这样做的,我正在从我的桌面上传一个文件来读取数据,但应用程序首先将其复制到另一个位置,然后从副本而不是原始副本读取数据。

    那你就可以走了。感谢@Bran和@techturl在评论中启发了我。

        2
  •  -1
  •   Christopher    7 年前

    您的问题很可能归结为糟糕的异常处理。在示例代码中,您接受异常,不记录它们的内容,然后继续跟踪致命的异常。这两种情况都是异常处理的致命错误。我估计你剩下的代码也有类似的问题。

    这些类型的表达式通常来自未正确关闭文件句柄。Wich确实与异常处理直接相关。因此,我只能像以前一样将这两篇文章链接起来,并希望您能根据他们的建议找到解决问题的方法:

    推荐文章