Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将现有数据库(存储文件)复制到存储文件夹_C#_Windows 8_Windows Store Apps - Fatal编程技术网

C# 将现有数据库(存储文件)复制到存储文件夹

C# 将现有数据库(存储文件)复制到存储文件夹,c#,windows-8,windows-store-apps,C#,Windows 8,Windows Store Apps,在我的Windows应用商店应用程序中,我想将现有数据库复制到存储文件夹。 我的数据库放在项目的主文件夹中 对于将数据表复制到存储文件夹,我使用以下代码(): 在VS调试模式下,所有这些都非常有效。 但如果我使用发布模式,或者只是停止调试并从Windows打开我的应用程序,它就不起作用了也没有引发异常。当尝试调用copyanc时,应用程序只是冻结0) { //从内存写入缓冲区 wait memStream.WriteAsync(buf,0,read); //将缓冲区写入文件 wait FileI

在我的Windows应用商店应用程序中,我想将现有数据库复制到存储文件夹。
我的数据库放在项目的主文件夹中

对于将数据表复制到存储文件夹,我使用以下代码():

在VS调试模式下,所有这些都非常有效。
但如果我使用发布模式,或者只是停止调试并从Windows打开我的应用程序,它就不起作用了
也没有引发异常。当尝试调用
copyanc
时,应用程序只是冻结<我敢肯定,那是我的
数据库文件=在释放模式下也为空

此外,我还尝试获取如下文件:

var uri = new Uri("ms-appx:///people.sqlite");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
但这并不能解决我的问题

问题:将现有数据库复制到存储文件夹的正确方法是什么

更新:

谢谢你们的回答,但我不能解决我的问题(

我使用CaliburnMicro实现MVVM

在我的视图模型上,当页面
加载时
我调用:

private async Task PrepareDatabase()
        {
            bool isDatabaseExisting;
            var storageFolder = ApplicationData.Current.LocalFolder; ;
            try
            {
                await storageFolder.GetFileAsync("database_name.sqlite");
                isDatabaseExisting = true;
            }
            catch
            {
                isDatabaseExisting = false;
            }
            if (!isDatabaseExisting)
            {
                StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("database_name.sqlite");
                await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
            }
        }
我的数据库:
Name-database\u Name.sqlite;

生成操作-Content;

复制到输出目录-始终复制;

当我从VisualStudio启动应用程序时,一切都正常运行。
然后我停止调试,从Windows运行应用程序-当它尝试打开此页面时,它会冻结。

在“Build Action”属性下,您会找到一个名为“Copy to Output Directory”的属性。请确保它设置为“Copy Always”

编辑:

还有另一种方法可以将文件包含在项目中,即嵌入资源

using System.Reflection;


public MainPage()
{
  this.InitializeComponent();
  Assembly asm = typeof(MainPage).GetTypeInfo().Assembly;
  Stream stream = asm.GetManifestResourceStream("YourNamespace.filename.extension");


  ConvertToFileAndCopyToLocalDirectory(stream);
}
在属性中,将构建操作设置为“嵌入式资源”


虽然我不确定它为什么会在调试中工作,但我假设您已经确保应用程序包清单包含.sqlite文件的声明

要检查的另一件事可能是,您在本地文件夹中是否已经有同名数据库。我预计会出现异常,但在执行CopySync时,我会使用重载指定文件名和冲突选项:

await latestFile.CopyAsync(ApplicationData.Current.LocalFolder,
    "My Db Name",
    NameCollisionOption.ReplaceExisting);
编辑:正如Arsalan00提到的,您可以使用嵌入式资源。我使用以下两个函数复制设置为嵌入式资源的数据库,以此进行测试:

    private const string DbBasePath = "MyApp.TestHelpers.TestDatabases.";    

    public static IAsyncOperation<IStorageFile> GetDbAsync(string dbName)
    {
        return Util.GetFileFromAssemblyResource(typeof(Data).GetTypeInfo().Assembly, DbBasePath + dbName, dbName, ApplicationData.Current.LocalFolder).AsAsyncOperation();
    }

    public static async Task<IStorageFile> GetFileFromAssemblyResource(Assembly ass, string resource, string filenameToCreate, IStorageFolder location)
    {
        IStorageFile file;
        // read for embedded resources
        using (var stream = ass.GetManifestResourceStream(resource))
        {
            var buf = new byte[stream.Length];
            // create file
            file = await location.CreateFileAsync(DateTime.Now.Ticks + filenameToCreate, CreationCollisionOption.ReplaceExisting);

            using (var memStream = new MemoryStream())
            {
                int read;
                // read bytes at a time from the embedded resource
                while ((read = await stream.ReadAsync(buf, 0, buf.Length)) > 0)
                {
                    // write from memory into buffer
                    await memStream.WriteAsync(buf, 0, read);
                    // write buffer to file
                    await FileIO.WriteBytesAsync(file, buf);
                }
            }
        }
        return file;
    }
private const string DbBasePath=“MyApp.TestHelpers.TestDatabases。”;
公共静态IAsyncOperation GetDbAsync(字符串dbName)
{
返回Util.GetFileFromAssemblyResource(typeof(Data).GetTypeInfo().Assembly,DbBasePath+dbName,dbName,ApplicationData.Current.LocalFolder).asAsAsAsyncOperation();
}
公共静态异步任务GetFileFromAssemblyResource(程序集ass、字符串资源、字符串文件名ToCreate、IStorageFolder位置)
{
IStorageFile文件;
//读取嵌入式资源
使用(var stream=ass.GetManifestResourceStream(资源))
{
var buf=新字节[stream.Length];
//创建文件
file=wait location.CreateFileAsync(DateTime.Now.Ticks+filenameToCreate,CreationCollisionOption.ReplaceExisting);
使用(var memStream=new MemoryStream())
{
int-read;
//从嵌入式资源一次读取字节
while((read=wait stream.ReadAsync(buf,0,buf.Length))>0)
{
//从内存写入缓冲区
wait memStream.WriteAsync(buf,0,read);
//将缓冲区写入文件
wait FileIO.WriteBytesAsync(文件,buf);
}
}
}
返回文件;
}

我觉得这个代码很正确。应该可以用

我只关心一件事: 你能复制所有函数并包括如何调用它吗


我假设您在某个地方缺少一些wait/async关键字。

@jimpanzer我也遇到了同样的问题,后来发现copyanc失败了(当我运行应用程序时,而不是在调试时)因为存在同名文件。此db文件是根据代码创建的,该代码用于在db文件不可用时获取数据。可能是您也在这样做。谢谢回复,但我已经尝试了所有类型的“复制到输出目录”-在发布模式下,或者如果我从Windows运行应用程序(不是从VS),它仍然无法工作。可能你还有其他想法吗?请检查我编辑的答案。检查是否在发布模式下获得有效流。如果是,可以将流转换回文件。谢谢回答,但它对我不起作用。检查更新的问题。谢谢。谢谢回答,但对我不起作用。检查更新的问题。谢谢。
    private const string DbBasePath = "MyApp.TestHelpers.TestDatabases.";    

    public static IAsyncOperation<IStorageFile> GetDbAsync(string dbName)
    {
        return Util.GetFileFromAssemblyResource(typeof(Data).GetTypeInfo().Assembly, DbBasePath + dbName, dbName, ApplicationData.Current.LocalFolder).AsAsyncOperation();
    }

    public static async Task<IStorageFile> GetFileFromAssemblyResource(Assembly ass, string resource, string filenameToCreate, IStorageFolder location)
    {
        IStorageFile file;
        // read for embedded resources
        using (var stream = ass.GetManifestResourceStream(resource))
        {
            var buf = new byte[stream.Length];
            // create file
            file = await location.CreateFileAsync(DateTime.Now.Ticks + filenameToCreate, CreationCollisionOption.ReplaceExisting);

            using (var memStream = new MemoryStream())
            {
                int read;
                // read bytes at a time from the embedded resource
                while ((read = await stream.ReadAsync(buf, 0, buf.Length)) > 0)
                {
                    // write from memory into buffer
                    await memStream.WriteAsync(buf, 0, read);
                    // write buffer to file
                    await FileIO.WriteBytesAsync(file, buf);
                }
            }
        }
        return file;
    }