none
关于文件流的释放的疑问 RRS feed

  • 问题

  • 本人写了一个代码,通过流的操作,生成静态网页。目前的疑问是,各个流的释放顺序是否正确,以及是否完整?(特别是那个HttpWebRequest request不知道要不要释放它)。

    局部代码如下:

    using

    {

    (此处省略了一些代码)

    do { count = count + 1; if (reader_toNewsData.HasRows) { HttpWebResponse response = null; Regex reg1 = new Regex(@"(?<=.+/).+(?=\.aspx)", RegexOptions.IgnoreCase); Match match1 = reg1.Match(sitePart_List[count]); string staticFileHead = match1.Value; while (reader_toNewsData.Read()) { int siteID = reader_toNewsData.GetInt32(0); string sitePath = siteHeader + sitePart_List[count] + "?id=" + siteID; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sitePath); try { response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string result = reader.ReadToEnd(); reader.Close(); stream.Close(); response.Close(); string savePath = Server.MapPath(@"Statesite\" + staticFileHead + siteID.ToString() + ".html"); StreamWriter writer = new StreamWriter(savePath, false, Encoding.UTF8); writer.Write(result); writer.Close(); } catch (WebException e2) { } } } } while (reader_toNewsData.NextResult()); reader_toNewsData.Close();

    }

    如果各位对代码的其他地方也有优化的建议,请不吝指教,谢谢!

    2012年8月7日 14:19

答案