【问题标题】:Save as, winforms (c#) [duplicate]另存为,winforms(c#)[重复]
【发布时间】:2020-12-03 20:21:17
【问题描述】:

我为“保存”按钮编写了这段代码

        {
            File.WriteAllText(ofd.FileName, textBox1.Text);
        }

我想做一个“另存为”按钮,通过我的应用程序创建一个文件,但我不知道该怎么做,有人知道怎么做吗?或者只是给我一个文档,谢谢。

【问题讨论】:

  • 这段代码如何保存任何东西?似乎是从文件中读取,而不是保存
  • 糟糕,代码错误!我会编辑它
  • 使用 SaveFileDialog。一旦用户浏览了新文件的位置,就可以通过 saveFileDialog.FileName 获得。将此值放入 File.WriteAllText 方法。
  • 看看SaveFileDialog In C# (C# Corner)。我希望这可以帮助您享受 C# 编码:How do I improve my knowledge in C#
  • 谢谢!我是新来的,为什么我的帖子有“-2”?

标签: c# winforms save-as


【解决方案1】:

使用“另存为”文件提示提示用户:

在表单上创建一个按钮。将 Click 事件设置为 btnSaveAsClick()。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
        {
            InitializeComponent();
        }

    private void btnSaveAs_Click(Object sender, EventArgs e)
    {
        String path = GetSaveFileName("usage.csv");
        if(String.IsNullOrEmpty(path)) return;
        //Write your file here using 'path'
    }

    private String GetSaveFileName(String SuggestedFileName)
    {
        SaveFileDialog ofd = new SaveFileDialog();
        ofd.FileName = SuggestedFileName;
        ofd.DefaultExt = "csv";
        ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        return ofd.ShowDialog()==DialogResult.OK ? ofd.FileName : "";
    }
}

如果这能解决您的问题,请记得点击绿色复选标记。

【讨论】:

  • 我的桌面没有创建文档,为什么?
  • @kichi 您必须出示您的代码,以便我们进一步提供帮助
  • OpenFileDialog ofd = new OpenFileDialog(); private void button4_Click(object sender, EventArgs e) { ofd.Filter = "Text | *.txt"; if(ofd.ShowDialog() == DialogResult.OK) { textBox1.Text = File.ReadAllText(ofd.FileName); } } private void button5_Click(object sender, EventArgs e) { File.WriteAllText(ofd.FileName, textBox1.Text); }
  • 使用 const 字符串代替 textBox1.Text,例如“测试”以验证 File.WriteAllText() 是否正常工作。
  • @kichi:SaveFileDialog 不保存任何内容。如果用户选择了一个文件,它会返回您,并且您可以从对象的实例中选择文件名 - 正如您在最后一行的“GetSaveFileName”方法中看到的那样。
猜你喜欢
  • 2011-07-01
  • 1970-01-01
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
相关资源
最近更新 更多