Reputation: 376
Hello, thanks for reading my question. I have a string that I need to put on a txt file.
I want to make it so that when the user clicks a button it asks for the folder, where the user wants to save this txt file, and generate it on in folder.
Here is some code I made but I do not know how to make it so that the user to chooses the folder.
private void Generar_Txt_Disco(string s_content, string s_folder)
{
//Ruta es donde se va a guardar
StreamWriter sr = new StreamWriter(s_folder);
//Vas escribiendo el texto
sr.WriteLine(s_content);
//Lo cierras
sr.Close();
}
Upvotes: 3
Views: 4671
Reputation: 1
public static string GetAnyPath(string fileName)
{
//my path where i want my file to be created is : "C:\\Users\\{my-system-name}\\Desktop\\Me\\create-file\\CreateFile\\CreateFile\\FilesPosition\\firstjson.json"
var basePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath.Split(new string[] { "\\CreateFile" }, StringSplitOptions.None)[0];
var filePath = Path.Combine(basePath, $"CreateFile\\CreateFile\\FilesPosition\\{fileName}.json");
return filePath;
}
replace .json with any type according to need also can refer https://github.com/swinalkm/create-file/tree/main/CreateFile/CreateFile for complete code
Upvotes: 0
Reputation: 60468
Use the SaveFileDialog
or FolderBrowserDialog
for that. (Member of System.Windows.Forms
)
SaveFileDialog Prompts the user to select a location for saving a file. This class cannot be inherited.
FolderBrowserDialog Prompts the user to select a folder. This class cannot be inherited.
private static void Generar_Txt_Disco(string s_content)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog()) == DialogResult.OK)
{
//Ruta es donde se va a guardar
StreamWriter sr = new StreamWriter(dialog.SelectedPath + "\\YourFileName.txt");
//Vas escribiendo el texto
sr.WriteLine(s_content);
//Lo cierras
sr.Close();
}
}
}
private static void Generar_Txt_Disco(string s_content)
{
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (dialog.ShowDialog()) == DialogResult.OK)
{
//Ruta es donde se va a guardar
StreamWriter sr = new StreamWriter(dialog.FileName);
//Vas escribiendo el texto
sr.WriteLine(s_content);
//Lo cierras
sr.Close();
}
}
}
Upvotes: 4
Reputation: 24403
Something like
using (SaveFileDialog sfd = new SaveFileDialog ())
{
if (sfd.ShowDialog() == DialogResult.OK)
{
//contains the path the user picked
string filepathToSave = sfd.FileName;
using (StreamWriter file = new StreamWriter(filepathToSave ))
{
file.WriteLine("foo");
}
}
}
Upvotes: 1