我试图从数据库中读取一行信息并将其写入 txt 文件。我已经弄清楚了大部分,但我收到以下错误“字段初始化程序无法引用非静态字段、方法或属性'reader_writer.filewriter.filePath'”,我不知道为什么。有人可以解释我的问题吗?
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();
}
}
}