浏览图像时,App.config中的连接字符串会发生变化

时间:2012-12-04 09:18:29

标签: c# connection-string datasource

以下是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浏览图像时,数据源中指定的路径将更改为浏览的图像文件的路径,从而引发异常以查找数据库。

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

1 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案是将RestoreDirectory设置为true:

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 ...
}