Save File to MyDocuments + App Folder
Asked Answered
R

2

12

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:

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
Rebellion answered 14/2, 2013 at 0:43 Comment(2)
Have you looked at the Directory.Exist()' method for the folder or if you know the full path you can check the File.Exist()` method also why are you using RegEx.Replace when you can use the built in string.Replace() method.. also your string.Format("{0}\\{1}" isn't that putting an extra 2 backslashes`\` in your path..?Breena
the "\\" is needed to escape the "\"Rebellion
C
33
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
}
Consonance answered 14/2, 2013 at 0:57 Comment(3)
CC...do you know how to set the path to the default MyDocs directory? My build is creating a new MyDocuments folder in my \bin\Debug\folder.Rebellion
@Rebellion I think I see why, check my answerConsonance
You should use string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),"MyApp","settings.dat");Cineaste
O
3

System.IO.Directory.CreateDirectory(Server.MapPath(path)); //you don't need to check if it exists first

Ostensory answered 22/4, 2015 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.