简体   繁体   English

在WPF应用程序中本地存储数据文件的文件夹

[英]Folder to store data files locally in WPF application

I currently have the code below in my WPF application which does exactly what I want it to do, however, upon publishing this it won't necessarily be able to access these folder locations as they won't be pointing to the correct directory nor will the folders exist. 我目前在我的WPF应用程序中有以下代码,它正是我想要它做的,但是,在发布它时,它不一定能够访问这些文件夹位置,因为它们不会指向正确的目录,也不会文件夹存在。

I was hoping somebody might be able to tell me what is the best way to save something into a local folder? 我希望有人能够告诉我什么是将东西保存到本地文件夹的最佳方法?

Whether it's inside the application folder itself or not is of no issue either. 它是否在应用程序文件夹本身内部也没有问题。

The code I'm currently using for the writing of the file: 我目前用于编写文件的代码:

using (Stream stream = File.Open(@"..\..\Templates\data.bin", FileMode.Create))
            {
                BinaryFormatter bin = new BinaryFormatter();
                bin.Serialize(stream, templateList);
            }

The code I'm currently using for the loading of the file: 我目前用于加载文件的代码:

using (Stream stream = File.Open(@"..\..\Templates\data.bin", FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();

            templateList = (List<Template>)bin.Deserialize(stream);
        }

You can use Environment.SpecialFolder to find an appropriate place to put files (for example, ApplicationData would be a good place to start). 您可以使用Environment.SpecialFolder查找放置文件的适当位置(例如,ApplicationData将是一个很好的起点)。 If you only need a temp file, you can use Path.GetTempFileName to create one. 如果您只需要临时文件,则可以使用Path.GetTempFileName创建一个。

Edit: One last note. 编辑:最后一个注释。 Storing stuff in the application folder itself can be a giant pain. 将东西存储在应用程序文件夹本身可能是一个巨大的痛苦。 Usually the application folder is created with the admin account during the installation so your app won't be able to write to it while running on a user account. 通常,应用程序文件夹是在安装期间使用管理员帐户创建的,因此您的应用程序在用户帐户上运行时将无法写入该文件夹。

You could use System.Environment.SpecialFolder.LocalApplicationData to store application specific data: 您可以使用System.Environment.SpecialFolder.LocalApplicationData来存储特定于应用程序的数据:

using System;

class Sample 
{
    public static void Main() 
    {
          Console.WriteLine("GetFolderPath: {0}", 
                 Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
    }
}

Ref: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx 参考: http//msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM