[英]How to create a txt file on a dynamically chosen folder
您好,感謝您閱讀我的問題。 我有一個字符串,需要放在 txt 文件中。
我想這樣做,當用戶單擊按鈕時,它會詢問用戶想要保存此 txt 文件的文件夾,並在文件夾中生成它。
這是我制作的一些代碼,但我不知道如何制作以便用戶選擇文件夾。
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();
}
為此使用SaveFileDialog
或FolderBrowserDialog
。 ( System.Windows.Forms
成員)
SaveFileDialog提示用戶選擇保存文件的位置。 這個類不能被繼承。
FolderBrowserDialog提示用戶選擇一個文件夾。 這個類不能被繼承。
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();
}
}
}
就像是
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");
}
}
}
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;
}
.json 根據需要替換成任意類型也可以參考https://github.com/swinalkm/create-file/tree/main/CreateFile/CreateFile完整代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.