下午,
我正在尝试编写一个表单,该表单将在我的一个数据库上运行查询并将结果放入文本文件中。
但是我无法完成文件的输出。有人能告诉我如何输出文件吗?我想我错过了一个输家,但我不知道该怎么做。
请告知。
A
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SwiftMSGDownload
{
public partial class Form1 : Form
{
string RdSqlMsg;
string RdSqlRef;
string RdSqlType;
string RdSqlTime;
string MSGRootPath;
public Form1()
{
InitializeComponent();
}
private void subGetMSGs_Click()
{
string Sql = null;
Sql = "SELECT [FileNumber] " + " ,[Reference] " + " ,[SenderRefID] " + " ,[Amount] " + " ,[Currency] " + " ,[Type] " + " ,[DateTransfer] " + " ,[Time] " + " ,[Msg] " + " ,[Direction] " + " ,[ProcessBy] " + " ,[SenderID] " + " ,[ReceiverID] " + " FROM [TransferFilesIn] " + " WHERE Time BETWEEN '" + txtLastTimeProcessed.Text + "' AND '" + DateTime.Now + "'" + " AND Type IN (199,103) " + " AND ReceiverID = 'ABCDEFXXX' ";
try
{
string strConnectionString = null;
strConnectionString = "Data Source=180.123.45.6;Password=thepassword;User ID=theuser;Initial Catalog=thedatabase;Persist Security Info = True";
txtSwiftDBConnectionString.Text = strConnectionString;
using (SqlConnection connObj = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdObj = new SqlCommand(Sql, connObj))
{
connObj.Open();
using (SqlDataReader readerObj = cmdObj.ExecuteReader())
{
//Loops through all returned records.
while (readerObj.Read())
{
RdSqlMsg = readerObj["Msg"].ToString();
RdSqlRef = readerObj["Reference"].ToString();
RdSqlType = readerObj["Type"].ToString();
RdSqlTime = readerObj["Time"].ToString();
RdSqlTime = RdSqlTime.Replace(":", "-");
RdSqlTime = RdSqlTime.Replace("/", "-");
string strFilePath = MSGRootPath + "\\" + RdSqlTime + "_" + RdSqlRef + "_" + RdSqlType + ".txt";
}
}
//Close the connection
connObj.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("subGetMSGs_Click - ERROR: " + Environment.NewLine + ex.Message);
return;
}
}
private void Form1_Load(object sender, EventArgs e)
{
MSGRootPath = "\\\\180.987.65.43\\Public\\Test";
}
private void btnStart_Click(object sender, EventArgs e)
{
subGetMSGs_Click();
}
}
答案 0 :(得分:0)
请参阅:
File.WriteAllText
http://msdn.microsoft.com/en-us/library/system.io.file.writealltext(v=vs.110).aspx
和
File.AppendAllText
http://msdn.microsoft.com/en-us/library/ms143356(v=vs.110).aspx
将文件路径和消息字符串传递给其中一种方法,它将写入一个文本文件。
答案 1 :(得分:0)
using System.Io;
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
while (readerObj.Read())
{
string something = "";
sw.writeline(something);
}
}
只需为读者返回的每个项目制作格式化的输出。