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

时间:2015-02-06 06:37:40

标签: c# winforms datagridview savefiledialog

我将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);
        }

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

2 个答案:

答案 0 :(得分:4)

您正在寻找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;

答案 1 :(得分:1)

你应该使用SaveFileDialog

        SaveFileDialog sfd = new SaveFileDialog();

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