我試圖從數據庫讀取一行信息並將其寫入一個txt文件。我大部分都想通了,但我得到以下錯誤「字段初始值設定項不能引用非靜態字段,方法或屬性'reader_writer.filewriter.filePath'」,我不知道爲什麼。有人能解釋我的問題嗎?將SQL信息寫入TXT文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Data.Common;
namespace reader_writer
{
public class filewriter
{
//public string filePath = "";
bool fileExists = false;
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbFile = filePath + @"\sqlfile.txt";
public void Main(string[] args)
{
fileExists = File.Exists(dbFile);
if (fileExists)
{
writeFileFromDB();
}
else
{
File.Create(dbFile);
writeFileFromDB();
}
}
public void writeFileFromDB()
{
//create connection
SqlCommand comm = new SqlCommand();
comm.Connection = new SqlConnection(@"MY DB CONNECTION STRING");
String sql = @"SELECT ROW1, ROW2
FROM Export.TABLENAME";
comm.CommandText = sql;
comm.Connection.Open();
SqlDataReader sqlReader = comm.ExecuteReader();
while (sqlReader.Read())
{
StreamWriter writer = File.CreateText(dbFile);
writer.WriteLine(sqlReader["ROW1"] + "\t" + sqlReader["ROW2"]);
writer.Close();
}
sqlReader.Close();
comm.Connection.Close();
}
}
}
的可能重複的[A字段初始不能引用非靜態字段,方法或屬性?](http://stackoverflow.com/questions/7400677/a-field-initializer-cannot-reference-the-non -static場法-或屬性) –