c# - 如何使用 using 指令包装流读取器?

标签 c# asp.net streamreader using

我的这段代码可以在一台 Windows Server 2008 R2 上运行,但不能在全新安装的 Server 2008 R2 上运行。下面的代码锁定了新服务器上的一些文本文件,但没有锁定旧服务器,这很奇怪。我非常确定这是这段代码,因为执行后文件立即被 w3wp 进程锁定。我有一个结束()标签,但我想将代码转换为封装在

using(StreamReader objStreamReader = default(StreamReader))
{
}  

我每次尝试封装时都会收到各种错误消息,因为有些东西只是变量或者不能与 using 指令一起使用。任何帮助或建议将不胜感激。该脚本的工作是解析一个文本文件,设置某些数据,例如下载到 download.text 引用,以便其他进程可以将解析后的数据输入到表中。

public void read_file()
{
try
{   
//Open a file for reading
string FILENAME = Server.MapPath("\\gwi_client\\gwi_user_data\\" + ds_user_data.FieldValue("um_login", null) + ".txt" );

//Read the file, displaying its contents

//Get a StreamReader class that can be used to read the file
StreamReader objStreamReader = default(StreamReader);
objStreamReader = File.OpenText(FILENAME);

//Now, read the entire file into a string
string contents = objStreamReader.ReadToEnd();

//Below gets string for download used in bytes
int a = contents.IndexOf("download-used=") ;

int b = contents.IndexOf("upload-used=") ;

string contents_a = contents.Substring(a);

string used_values_a = contents_a.Replace(contents.Substring(b), " ") ;

string download_used_bytes = used_values_a.Replace("download-used="," ");

download_used_txt.Text = download_used_bytes ;  

//Below gets string for upload used in bytes
int c = contents.IndexOf("upload-used=") ;

int d = contents.IndexOf("last-seen=") ;

string contents_b = contents.Substring(c);

string used_values_b = contents_b.Replace(contents.Substring(d), " ") ;

string upload_used_bytes = used_values_b.Replace("upload-used="," ");

upload_used_txt.Text = upload_used_bytes ;

objStreamReader.Close();

}
catch (Exception ex)
{
Session["um_login"] = ds_user_data.FieldValue("um_login", null) ;
Session["sess_insert_um"] = "Y" ;

}
Session["um_login"] = ds_user_data.FieldValue("um_login", null) ;
Session["sess_insert_um"] = "Y" ;

}

最佳答案

你应该这样做:

using (StreamReader objStreamReader = File.OpenText(FILENAME))
{
   //code here
}

关于c# - 如何使用 using 指令包装流读取器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843993/

相关文章:

c# - JavaScript 未定义属性

asp.net - 有人可以解释一下 jQuery/Javascript 中这种看似不一致的情况吗? (读取时尾括号不一致)

asp.net - 仅具有共享函数的类 - 为什么它不好?

c# - JavaScript 函数在 C# 中返回 bool 值

c# - 从 StreamReader.ReadLine() 获取的字符串的编码是什么

c# - 在 C# 中的一行中读取不同的数据类型

c# - 由旧 C 代码编写的文件,已移至 C#

c# - 文件计数保存在哪里?

c# - 离开 StreamReader 而不关闭 Stream

c# - 如何避免值类型的装箱