将文件保存到 Windows Form C# 中的特定文件夹

Save file to a specific folder in Windows Form C#

我正在尝试将一些 selected 文件保存在我的应用程序中的文件夹(图像)中

我可以使用以下代码获取文件:

         private void button1_Click(object sender, EventArgs e)
    {

        string imagelocation = "";

        OpenFileDialog dialog = new OpenFileDialog();

        if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
        {
            textBox2.Text = dialog.FileName;
        }
    }

为了保存我在 textBox2 中获得的文件,我尝试了以下代码。但是使用以下代码我还必须 select 我要保存文件的路径。 如果我想(如图所示将我的路径永久设置为 'images' 文件夹)进行保存怎么办?

       private void button2_Click(object sender, EventArgs e)
    {


        SaveFileDialog f = new SaveFileDialog();

        if(f.ShowDialog() == DialogResult.OK)
        {
            using(Stream s = File.Open(f.FileName, FileMode.CreateNew))
            using(StreamWriter sw =  new StreamWriter(s))
            {
                sw.Write(textBox2.Text);
            }
        }
     }

2 种解决此问题的方法


  • 第一种方法:(浏览文件并点击保存,自动将选中的文件保存到图片目录)


    private void button2_Click(object sender, System.EventArgs e)
    {

        var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
        var imageDir = Path.Combine(assemblyParentPath, "Image");

        if (!Directory.Exists(imageDir))
            Directory.CreateDirectory(imageDir);


         using (Stream s = File.Open(imageDir+"\"+Path.GetFileName(textBox1.Text), FileMode.CreateNew))
         using (StreamWriter sw = new StreamWriter(s))
         {
                     sw.Write(textBox1.Text);
         }

     }


  • 第二种方法:(浏览文件并保存打开保存对话框,目录作为图像目录,文件名作为先前选择的文件)
private void button2_Click(object sender, System.EventArgs e)
        {

            var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var assemblyParentPath = Path.GetDirectoryName(assemblyPath);
            var imageDir = Path.Combine(assemblyParentPath, "Image");

            if (!Directory.Exists(imageDir))
                Directory.CreateDirectory(imageDir);

            SaveFileDialog f = new SaveFileDialog();
            f.InitialDirectory = imageDir;
            f.FileName = textBox1.Text;
            if (f.ShowDialog() == DialogResult.OK)
            {
                using (Stream s = File.Open(imageDir + "\" + Path.GetFileName(textBox1.Text), FileMode.CreateNew))
                using (StreamWriter sw = new StreamWriter(s))
                {
                    sw.Write(textBox1.Text);
                }

            }
        }```

这个代码对你有用吗?

private void button1_Click(object sender, EventArgs e)
{
    var dlg = new OpenFileDialog();
    dlg.Title = "Select Picture";
    dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
    dlg.Filter = "Common Picture Files|*.gif;*.png;*.bmp;|All Files|*.*";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = dlg.FileName;
    }
}