C# 将文件保存到 MyDocuments + App 文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14865963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save File to MyDocuments + App Folder
提问by Jeagr
I am trying to save my .NET application settings file to the user's %MyDocument%\MyApplication folder, but I don't know how to check for an existing folder\file, and create or append the folder\file on save. I don't want to open a saveFileDialog because I need the file to be in the same place on all user computers. This is what I have so far, but it isn't working. Any help would be appreciated:
我正在尝试将我的 .NET 应用程序设置文件保存到用户的 %MyDocument%\MyApplication 文件夹,但我不知道如何检查现有文件夹\文件,并在保存时创建或附加文件夹\文件。我不想打开 saveFileDialog 因为我需要该文件在所有用户计算机上都位于同一位置。这是我到目前为止所拥有的,但它不起作用。任何帮助,将不胜感激:
var saveSettings = settingsList.text; //assign settings to a variable
saveSettings = Regex.Replace(saveSettings, @"\s+", "").Trim() + Environment.NewLine; //remove any extra spaces and add a carriage return so that each setting is on a new line
var fileName = string.Format("{0}\{1}", Environment.SpecialFolder.MyDocuments + "\MyApp\", "settings.dat"); //generate path to settings.dat
File.AppendAllText(fileName, saveSettings); //save settings.dat
采纳答案by CC Inc
string path = System.IO.Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDoc??uments),"MyApp","settings.dat");
if(Directory.Exists(path))
{
//Exists
}
else
{
//Needs to be created
}
回答by user2378769
System.IO.Directory.CreateDirectory(Server.MapPath(path)); //you don't need to check if it exists first
System.IO.Directory.CreateDirectory(Server.MapPath(path)); //你不需要先检查它是否存在