如果db文件已嵌入,则无法访问它以添加/删除行等。 为什么要将构建操作更改为Embedded Resource?将内容放在内容中会更好,因此db是一个与exe不同的文件(但仍位于同一目录中),然后构建db文件的路径(即使用Application.StartupPath)。
无论如何,如果你想将它设置为嵌入式,你需要在运行时提取数据库,并在使用之前将它存储在某个地方。
这里是可以提取嵌入的资源文件(当然,您需要更改文件名,或者把它作为参数)的方法:
private void ExtractFromAssembly()
{
string strPath = Application.LocalUserAppDataPath + "\\MyFile.db";
if (File.Exists(strPath)) return; // already exist, don't overwrite
Assembly assembly = Assembly.GetExecutingAssembly();
//In the next line you should provide NameSpace.FileName.Extension that you have embedded
var input = assembly.GetManifestResourceStream("MyFile.db");
var output = File.Open(strPath, FileMode.CreateNew);
CopyStream(input, output);
input.Dispose();
output.Dispose();
System.Diagnostics.Process.Start(strPath);
}
private void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write(buffer, 0, read);
}
}
该文件将在被复制本地应用程序路径,位于用户目录中。这将在应用程序第一次启动时完成,否则db文件将在每次启动应用程序时被覆盖(用exe中的clean db软件包覆盖)
为了说明,我不需要访问数据库添加或删除行,它纯粹是一个参考数据库。它存储邮政编码,地区代码及其相应的位置。因此,鉴于此方面,嵌入式资源是否成为一个好的或充足的选择? –
如果它包含数据,我想你需要使用这些数据。所以你需要访问数据库。要访问它,您需要从Embedded Resource中提取它并将其另存为一个单独的文件。 – Fabske
好的,谢谢你的澄清。我刚刚发现实际问题是OleDB没有在机器上注册 –