Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从MS SQL下载/上载文件后,文件将无法读取_C#_Sql - Fatal编程技术网

C# 从MS SQL下载/上载文件后,文件将无法读取

C# 从MS SQL下载/上载文件后,文件将无法读取,c#,sql,C#,Sql,我有ASP MVC应用程序、MS SQL和C#。我将一个文件下载到MS SQL,然后从DB上传该文件。在此之后,文件将无法读取。我不明白发生了什么。下面的代码将文件返回给客户端 public string CreateFile(HttpPostedFileBase file) { string stream_id = String.Empty; try { int size = file.ContentLength

我有ASP MVC应用程序、MS SQL和C#。我将一个文件下载到MS SQL,然后从DB上传该文件。在此之后,文件将无法读取。我不明白发生了什么。下面的代码将文件返回给客户端

public string CreateFile(HttpPostedFileBase file)
    {
        string stream_id = String.Empty;

        try
        {
            int size = file.ContentLength;
            string name = file.FileName;               
            string contentType = file.ContentType;
            byte[] bytes = new byte[size];
            file.InputStream.Read(bytes, 0, size);

            string constr = ConfigurationManager.ConnectionStrings["PokrovConnectionString"].ConnectionString;

            using (TransactionScope ts = new TransactionScope())
            {
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "DECLARE @MyTableVar TABLE (stream_id uniqueidentifier);"
                        + "INSERT INTO Files(name, file_stream) OUTPUT INSERTED.stream_id INTO @MyTableVar VALUES(@name, @file_stream);"
                        + "SELECT TOP (1) @Identity = stream_id FROM @MyTableVar;";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = Path.GetFileName(file.FileName);
                        cmd.Parameters.Add("@file_stream", SqlDbType.VarBinary).Value = bytes;
                        SqlParameter idParam = cmd.Parameters.Add("@Identity", SqlDbType.NVarChar, 1000);
                        idParam.Direction = ParameterDirection.Output;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        stream_id = (string)idParam.Value;
                    }
                }
                ts.Complete();
            }
        }
        catch { }

        return stream_id;

    }

    public FileContentResult GetFile(Guid stream_id,  string contentType = "application/octet-stream")
    {
        SqlDataReader rdr;
        byte[] fileContent = null;
        string mimeType = "";
        string fileName = "";
        string connect = onfigurationManager.ConnectionStrings["PokrovConnectionString"].ConnectionString;
        bool success = false;

        using (var conn = new SqlConnection(connect))
        {
            var qry = "SELECT file_stream, name, file_type FROM Files WHERE stream_id = @stream_id";
            var cmd = new SqlCommand(qry, conn);
            cmd.Parameters.AddWithValue("@stream_id", stream_id);
            conn.Open();

            try
            {
                rdr = cmd.ExecuteReader();
                if (rdr.HasRows)
                {
                    rdr.Read();
                    fileContent = (byte[])rdr["file_stream"];
                    mimeType = rdr["file_type"].ToString();
                    fileName = rdr["name"].ToString();
                }
                success = true;
            }
            catch
            {
                return null;
            }
        }

        if (success == true)
        {
            FileContentResult newFile = new FileContentResult(fileContent, contentType);
            newFile.FileDownloadName = fileName;
            return newFile;
        }
        return null;
    }

通过查看将发布的文件存储到数据库中的代码,很可能您忘记了复制实际的文件内容,只是用发布文件的长度初始化了空字节数组,并将其保存到数据库中

Net有一个类,它可以帮助您将流保存到sql server中,而无需先分配缓冲区并读取整个流—SqlBytes。尝试替换此行:

byte[]bytes=新字节[file.ContentLength]

为此:

SqlBinary bytes=新的SqlBinary(file.InputStream)


您还可以在中查看SqlBinary的用法。

不可读是什么意思?我希望我能理解他对文件的看法。不可读的文件是数据库文件吗?例如,如果是图像,我无法用Paint打开它,或者如果是MS World文件,当我打开它时,没有读取字符。是否为FileContentResult填充FileContents属性?您能否显示保存/加载文件二进制数据的代码片段?