日期:2014-05-18  浏览次数:20381 次

访问文件时,这个问题如何解决,谢谢各位啦!
下面这段代码老是提醒说
编译器错误信息: CS0165: 使用了未赋值的局部变量“sw”
源错误:

行 42: finally
行 43: {
行 44: sw.Close();
行 45: }
行 46: }

大家帮忙给看看,先谢啦!

 protected void Button1_Click(object sender, EventArgs e)
  {
  StreamWriter sw;
  string filePath = Server.MapPath("text.txt");
  try
  {
  if (File.Exists(filePath))
  {
  sw = File.AppendText(filePath);
  }
  else
  {
  sw = File.CreateText(filePath);
  }
  sw.WriteLine("Name:" + TextBox1.Text.Trim());
  sw.WriteLine("Sex:" + TextBox2.Text.Trim());
  sw.WriteLine("Age:" + TextBox3.Text.Trim());
  sw.WriteLine("---------------------------");
  Label1.Text = "信息保存成功!";
  }
  catch (Exception ex)
  {
  Label1.Text = "信息保存失败!";
  }
  finally
  {
  sw.Close();
  }
  }


------解决方案--------------------
不用那么麻烦,这样就可以了:
string filePath = Server.MapPath("text.txt"); 
StreamWriter sw = new StreamWriter(filePath, false);
try
{
sw.WriteLine("Name:" + TextBox1.Text.Trim());
sw.WriteLine("Sex:" + TextBox2.Text.Trim());
sw.WriteLine("Age:" + TextBox3.Text.Trim());
sw.WriteLine("---------------------------");
Label1.Text = "信息保存成功!";
}
catch (Exception ex)
{
Label1.Text = "信息保存失败!";
}
finally
{
sw.Close();
}
------解决方案--------------------
C# code
protected void Button1_Click(object sender, EventArgs e)
{
  string filePath = Server.MapPath("text.txt");
  using (StreamWriter sw = File.AppendText(filePath))
  {
    try
    {
      sw.WriteLine("Name:" + TextBox1.Text.Trim());
      sw.WriteLine("Sex:"  + TextBox2.Text.Trim());
      sw.WriteLine("Age:"  + TextBox3.Text.Trim());
      sw.WriteLine("---------------------------");
      Label1.Text = "信息保存成功!";
    }
    catch (Exception ex)
    {
      Label1.Text = "信息保存失败!";
    }
  }
}

------解决方案--------------------
1楼的一样没有赋值。2楼的可以使用!
------解决方案--------------------
1楼,你测过吗?我测了一下你的好像不行哦
protected void Button2_Click(object sender, EventArgs e)
{
string filePath = Server.MapPath("text.txt");
StreamWriter sw;
if (File.Exists(filePath))
{
sw = File.AppendText(filePath);
}
else
{
sw = File.CreateText(filePath);
}

try
{
sw.WriteLine("Name:" + TextBox1.Text.Trim());
sw.WriteLine("Sex:" + TextBox2.Text.Trim());
sw.WriteLine("Age:" + TextBox3.Text.Trim()); 
sw.WriteLine("---------------------------");
Label1.Text = "信息保存成功!";
}
catch
{
Label1.Text = "信息保存失败!";
}
finally
{
sw.Close();
}
}

ps:使用时需要在web.config文件中的<system.web>加入<identity impersonate="true"/>提升