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

C# 用于在WPF应用程序中本地存储数据文件的文件夹,c#,directory,C#,Directory,我目前在我的WPF应用程序中有下面的代码,它正是我想要它做的,但是,发布后它不一定能够访问这些文件夹位置,因为它们不会指向正确的目录,文件夹也不会存在 我希望有人能告诉我什么是将内容保存到本地文件夹的最佳方法 它是否在应用程序文件夹中也没有问题 我当前用于写入文件的代码: using (Stream stream = File.Open(@"..\..\Templates\data.bin", FileMode.Create)) { Bin

我目前在我的WPF应用程序中有下面的代码,它正是我想要它做的,但是,发布后它不一定能够访问这些文件夹位置,因为它们不会指向正确的目录,文件夹也不会存在

我希望有人能告诉我什么是将内容保存到本地文件夹的最佳方法

它是否在应用程序文件夹中也没有问题

我当前用于写入文件的代码:

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

            templateList = (List<Template>)bin.Deserialize(stream);
        }
我当前用于加载文件的代码:

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

            templateList = (List<Template>)bin.Deserialize(stream);
        }
使用(Stream=File.Open(@.\..\Templates\data.bin),FileMode.Open))
{
BinaryFormatter bin=新的BinaryFormatter();
templateList=(列表)bin.Deserialize(流);
}

您可以使用Environment.SpecialFolder找到放置文件的适当位置(例如,ApplicationData是一个很好的起点)。如果只需要临时文件,可以使用Path.GetTempFileName创建一个临时文件


编辑:最后一个注释。将内容存储在应用程序文件夹本身可能是一个巨大的难题。通常,应用程序文件夹是在安装过程中使用管理员帐户创建的,因此应用程序在使用用户帐户运行时将无法写入该文件夹。

您可以使用
System.Environment.SpecialFolder.LocalApplicationData
存储特定于应用程序的数据:

using System;

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

Ref:

我不确定我的问题是否正确,也许这就是你想要的?非常感谢Matt。我使用了Environment.SpecialFolder,只需执行一个简单的检查,看看目录是否存在,如果不存在,就会创建新文件夹。全部完成!