【问题标题】:How to create a txt file on a dynamically chosen folder如何在动态选择的文件夹上创建 txt 文件
【发布时间】:2012-01-17 15:37:57
【问题描述】:

您好,感谢您阅读我的问题。我有一个字符串需要放在 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();           
}

【问题讨论】:

标签: c# file


【解决方案1】:

说明

为此使用SaveFileDialogFolderBrowserDialog。 (System.Windows.Forms的成员)

SaveFileDialog 提示用户选择保存文件的位置。这个类不能被继承。

FolderBrowserDialog 提示用户选择一个文件夹。这个类不能被继承。

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();
        }
    }
}

SaveFileDialog 示例

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();
        }
    }
}

更多信息

【讨论】:

  • 释放使用ShowDialog 打开的对话框是一种很好的做法,因为它们在关闭时不会自动释放。
  • 好点,我的答案已更新。所有实现IDisposable 的东西都应该被处理掉。谢谢
  • 很高兴为您提供帮助!祝你有美好的一天。
  • 有没有方法也可以询问文件名?
  • 当然,使用第二个示例。这要求提供文件路径和名称。
【解决方案2】:

类似

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");
      }
  }
}

【讨论】:

    【解决方案3】:
        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 完整代码

    【讨论】: