gpt4 book ai didi

c# - 浏览图像时 App.config 中的连接字符串发生变化

转载 作者:太空宇宙 更新时间:2023-11-03 16:21:45 25 4
gpt4 key购买 nike

下面是app.config文件中的连接字符串,注意数据源中指定的路径。

<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\..\Database\ProductsDatabase.accdb;Persist Security Info=False;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

应用程序在带有 MouseDoubleclick 事件的按钮控件内有一个图像控件。

                        <Button Name="m_oBtnProductImage" Grid.Column="0"  Height="60" Width="60" Background="LightGray" Style="{x:Null}" MouseDoubleClick="m_oBtnProductImage_MouseDoubleClick">
<Image Tag="Image" Name="m_oImage" Stretch="Fill" Source="{Binding SelectedProductEn.ProductImage}"></Image>
</Button>

MouseDoubleclick 事件处理程序具有浏览和上传新图像以及在数据库中更新相同图像的功能。

private void m_oBtnProductImage_MouseDoubleClick(object sender, RoutedEventArgs e)
{
Bitmap oBitmapImage = null;
OpenFileDialog oBrowseImageFile = new OpenFileDialog();
oBrowseImageFile.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (oBrowseImageFile.ShowDialog() == true)
{
System.Windows.Controls.Image oPictureBox = ((Button)sender).FindName("m_oImage") as System.Windows.Controls.Image;
string sImagePath = oBrowseImageFile.FileName;
oBitmapImage = new Bitmap(sImagePath);
((CMainUIViewModel)this.DataContext).SelectedProductEn.ProductImage = (byte[])TypeDescriptor.GetConverter(oBitmapImage).ConvertTo(oBitmapImage, typeof(byte[]));
((CMainUIViewModel)this.DataContext).UpdateModifiedProduct(((CMainUIViewModel)this.DataContext).SelectedProductEn);
}
}

当从应用程序的 UI 浏览图像时,数据源中指定的路径更改为浏览图像文件的路径,从而抛出找不到数据库的异常。

进行适当更改所需的建议。

最佳答案

一个快速而肮脏的解决方案是设置 RestoreDirectory为真:

oBrowseImageFile.RestoreDirectory = true;
if (oBrowseImageFile.ShowDialog())
{
...
}

更好的解决方案是避免在连接字符串中使用相对路径,例如

  • 使用 |DataDirectory|在你的连接字符串中

  • 在您的应用程序启动时调用 AppDomain.CurrentDomain.SetData("DataDirectory", somepath) 以设置 |DataDirectory| 引用的位置。例如,您可以将其设置为包含可执行文件的目录,如下所示:

    AppDomain.CurrentDomain.SetData("DataDirectory", 
    AppDomain.CurrentDomain.BaseDirectory);

顺便说一句,OpenFileDialog 实现了 IDisposable,因此您应该真正调用 IDisposable.Dispose,可能使用 using声明:

using (OpenFileDialog oBrowseImageFile = new OpenFileDialog())
{
oBrowseImageFile.Filter = ...
... etc ...
}

关于c# - 浏览图像时 App.config 中的连接字符串发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13699507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com