我想使用文本文件上的Windows服务从服务器数据库中检索数据?我可以这样做吗?我将如何做到这一点?我的意思是我知道创建窗口服务但我对SQL连接和文件感到困惑写部分在哪里执行它?我尝试了一些东西
class Program
{
static void Main(string[] args)
{
RunSchedule();
}
public static void RunSchedule()
{
string path = Path.GetFullPath("d:\\MyTest") + "\\" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
try
{
if (!File.Exists(path))
{
File.Create(path);
SqlConnection conn = new SqlConnection("Data Source=...;Initial Catalog=Test;User ID=s_a;Password=sa56ta112;");
String sql = @"SELECT Id,UserName, Email,Password,CreatedDate
FROM Register";
SqlCommand com = new SqlCommand();
com.CommandText = sql;
//com.Connection = conn;
conn.Open();
StreamWriter tw = File.AppendText("d:\\MyTest");
SqlDataReader reader = com.ExecuteReader();
tw.WriteLine("Id,UserName,Email,Password,CreatedDate");
while (reader.Read())
{
tw.Write(reader["Id"].ToString());
tw.Write(" , " + reader["UserName"].ToString());
tw.Write(" , " + reader["Email"].ToString());
tw.Write(" , " + reader["Password"].ToString());
tw.Write(" , " + reader["CreatedDate"].ToString());
}
tw.WriteLine(DateTime.Now);
tw.WriteLine("---------------------------------");
tw.Close();
reader.Close();
conn.Close();
}
}
catch (Exception ex)
{
string errorLogPath = @"D:\MyTest.txt";
File.AppendAllText(errorLogPath, Environment.NewLine + ex.Message);
}
}
}
我正确地做到了吗?请指导我。
答案 0 :(得分:0)
while (reader.Read())
{
row = new DataRow();
row.ItemArray = new object[reader.FieldCount];
reader.GetValues(row.ItemArray);
foreach (object item in row.ItemArray)
{
streamWriter.Write((string)item + "\t");
}
streamWriter.WriteLine();
}
答案 1 :(得分:0)
如果你得到"访问路径' d:\ MyTest'被拒绝。"错误,而不是转到解决方案资源管理器中的txt文件属性,而不是更改复制到输出目录属性从不复制到复制如果更新或复制总是