2015-02-06 61 views
-1

我正在导出datagridview的数据转换成文本文件的格式, 创建我尝试下面的代码请保存位置的文本文件中使用C#

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

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

+0

窗口或网页??? – 2015-02-06 06:38:31

+0

@Ganesh_Devlekar,Windows桌面应用程序。 – 2015-02-06 06:39:22

+1

注意:使用'IDisposable'工作时,将它包装成''using',在你的情况下'使用(StreamWriter sW = new StreamWriter ...){...}' – 2015-02-06 06:42:04

回答

4

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

谢谢:-)它解决了我的问题:-) – 2015-02-06 08:09:49

+0

欢迎您,非常高兴它没有 – chouaib 2015-02-06 08:19:21

1

你应该使用SaveFileDialog

 SaveFileDialog sfd = new SaveFileDialog(); 

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