c# - 将二进制文件保存到数据库

标签 c# .net vb.net visual-studio visual-studio-lightswitch

我知道这个主题有很多话题,我已经尝试实现(翻译)this one从 VB 到 C#。

Table fileContainer = {string FileName, binary File}

这是我的尝试:

partial void FileContainersAddAndEditNew_Execute()
{
    Dispatchers.Main.BeginInvoke(() =>
    {

        OpenFileDialog openDialog = new OpenFileDialog();

        if (openDialog.ShowDialog() == true)
        {
            using (System.IO.FileStream fileData = openDialog.File.OpenRead())
            {
                long fileLen = fileData.Length;

                if (fileLen > 0)
                {
                    Byte[] fileBArray = new Byte[fileLen];

                    fileData.Read(fileBArray, 0, fileLen);
                    fileData.Close();

                    FileContainer fc = this.FileContainers.AddNew();

                    fc.File = fileBArray;
                    fc.FileName = openDialog.File.Extension.ToString().ToLower();

                }
            }
        }

    });
}

但是代码在这一行失败了:

 FileContainer fc = this.FileContainers.AddNew();

出现此错误:

IVisualCollection<T>.AddNew() should not be called from UI Thread.

我有点困惑。我认为:

 Dispatchers.Main.BeginInvoke(() =>

阻止了这种情况的发生。还是我做错了?

我注意到的另一件事是 VB 代码使用:

filenLen-1

但我越界了。他们也不会将其转换为 int,但 .Read 不会将 long 作为参数。

最佳答案

openFileDialog.ShowDialog() 不返回 bool 值,不能在这样的 if 语句中使用。 openFileDialog.ShowDialog() 将打开对话框。据我所知,执行会暂停,直到您关闭对话框,并且没有理由检查它是否打开。

filenLen-1

using (System.IO.FileStream fileData = openDialog.File.OpenRead());

long fileLen = fileData.Length;

应该是

filenLen--;

using (System.IO.FileStream fileData = System.IO.File.OpenRead(openDialog.FileName))

int fileLen = int.Parse(fileData.Length.ToString());

fileData.Read(fileBArray, 0, fileLen); 需要 fileLen 为整数。 fileData 返回一个 long 是有原因的,这可能会导致问题。

至于调用问题,我必须确切地知道您要做什么才能帮助您。也许我们可以避免调用。

关于c# - 将二进制文件保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15968072/

相关文章:

.net - 将 Windows 服务类添加到类库

.net - VB.NET 窗口屏幕截图 (ALT+PRINTSCREEN)

C# 将 JSON 反序列化为对象

c# - 如何使用word interop判断两个word文档是否相同

c# - 获取一个月中的星期六

c# - Windows 7 中的 .NET 模拟(不允许请求的注册表访问)

c# - 为来自 .NET Windows 服务的新线程设置 CultureInfo

c# - MVC Controller 冒泡回到路由器?

.net - `SELECT MIN(ZoneMin), MAX(ZoneMin) FROM Plant` 作为 LINQ to SQL

xml - 有没有办法在应用程序设置中使用字典或 xml?