询问位置以保存使用 C# 创建的文本文件

Ask location to save text file created using c#

我正在将 datagridview 数据导出为文本文件格式, 我尝试了下面的代码

        string dirLocationString = @"C:\Users\palanar\Desktop\result.txt";
        StreamWriter sW = new StreamWriter(dirLocationString);
        string lines = "";
        lines = "DateTime" + "\t" + "TestStatus" + "\t" + "BatPackSN" + "\t" + "CellSN"
                + "\t" + "BlockSN" + "\t" + "UI_ID" + "\t" + "UI_ParentID" + "\t" + "OperationNumber"
                + "\t" + "OperationName" + "\t" + "EquipmentNumber" + "\t" + "EquipmentName" + "\t" + "WorkOrder"
                + "\t" + "Assembly" + "\t" + "ProductName" + "\t" + "HandlingDuration" + "\t" + "OperationDuration"
                + "\t" + "RepairID" + "\t" + "DefectID" + "\t" + "UitemLevelCode" + "\t" + "UIEventLevelCode";
        sW.WriteLine(lines);
        for (int row = 0; row < dataGridView2.Rows.Count - 1; row++)
        {
            string lines1 = "";
            for (int col = 0; col <= 19; col++)
            {
                lines1 += (string.IsNullOrEmpty(lines1) ? " " : "\t") + dataGridView2.Rows[row].Cells[col].Value.ToString();
            }

            sW.WriteLine(lines1);
        }

此处数据完美导出并以文本文件格式保存,问题是我在这里指定了默认位置,而不是它应该通过打开保存对话框询问位置。

您正在寻找 saveFileDialog this is a tutorial

示例:

SaveFileDialog sfd = new SaveFileDialog();

sfd.Filter = "Text file(*.txt)|*.txt";
sfd.FilterIndex = 1;

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return; }
string dirLocationString = sfd.FileName;

你应该使用SaveFileDialog

        SaveFileDialog sfd = new SaveFileDialog();

        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            //your selected file location 
            string dirLocationString = sfd.FileName;
        }