问题描述:

Below is the connection string inside app.config file.Notice the specified path in datasource.

<?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>

The application has an image control inside a button control with a MouseDoubleclick event.

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

The MouseDoubleclick event handler has functionality to browse and upload a new image and than update the same in database.

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);

}

}

When an image is browsed from application's UI,the path specified in the datasource changes to path of the browsed image file,thereby throwing an exception for not finding the database.

Suggestions needed to make appropriate changes.

网友答案:

A quick and dirty solution would be to set RestoreDirectory to true:

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

A better solution is to avoid using a relative path in your connection string, e.g.

  • use |DataDirectory| in your connection string

  • call AppDomain.CurrentDomain.SetData("DataDirectory", somepath) when your application starts up to set the location referenced by |DataDirectory|. For example, you could set it to the directory containing your executable as follows:

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

Incidentally, OpenFileDialog implements IDisposable, so you should really call IDisposable.Dispose, probably with a using statement:

using (OpenFileDialog oBrowseImageFile = new OpenFileDialog())
{
    oBrowseImageFile.Filter = ...
    ... etc ...
}
相关阅读:
Top