当前位置: 首页>>代码示例>>C#>>正文


C# StreamReader.Dispose方法代码示例

本文整理汇总了C#中System.IO.StreamReader.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.Dispose方法的具体用法?C# StreamReader.Dispose怎么用?C# StreamReader.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.StreamReader的用法示例。


在下文中一共展示了StreamReader.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            string input = sr.ReadToEnd();
            sr.Dispose();

            JavaScriptSerializer ser = new JavaScriptSerializer();
            dynamic json = ser.DeserializeObject(input);
            for (int i = 1; i < json.Length; i++)
            {
                dynamic block = json[i];
                string blockType = block[0];
                Dictionary<string, object> blockAttr = block[1];

                for (int j = 2; j < block.Length; j++)
                {
                    dynamic span = block[j];
                    string spanType = span[0];
                    string text = span[1];
                    Console.Write(text);
                }

                Console.WriteLine();
                Console.WriteLine();
            }
        }
开发者ID:sheremetyev,项目名称:text-json,代码行数:26,代码来源:cat.cs

示例2: GetExistAccessToken

 /// 获取token,如果存在且没过期,则直接取token
 /// <summary>
 /// 获取token,如果存在且没过期,则直接取token
 /// </summary>
 /// <returns></returns>
 public static string GetExistAccessToken()
 {
     // 读取XML文件中的数据
     string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLToken.xml");
     FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
     StreamReader str = new StreamReader(fs, System.Text.Encoding.UTF8);
     XmlDocument xml = new XmlDocument();
     xml.Load(str);
     str.Close();
     str.Dispose();
     fs.Close();
     fs.Dispose();
     string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText;
     DateTime AccessTokenExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText);
     //如果token过期,则重新获取token
     if (DateTime.Now >= AccessTokenExpires)
     {
         AccessToken mode = Getaccess();
         //将token存到xml文件中,全局缓存
         xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.access_token;
         DateTime _AccessTokenExpires = DateTime.Now.AddSeconds(mode.expires_in);
         xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _AccessTokenExpires.ToString();
         xml.Save(filepath);
         Token = mode.access_token;
     }
     return Token;
 }
开发者ID:shinygang,项目名称:Wechat-JSSDK,代码行数:32,代码来源:JSSDK.cs

示例3: DisposeObject

 private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response,
     ref Stream responseStream, ref StreamReader reader)
 {
     if (request != null)
     {
         request = null;
     }
     if (response != null)
     {
         response.Close();
         response = null;
     }
     if (responseStream != null)
     {
         responseStream.Close();
         responseStream.Dispose();
         responseStream = null;
     }
     if (reader != null)
     {
         reader.Close();
         reader.Dispose();
         reader = null;
     }
 }
开发者ID:superhappy123,项目名称:Test,代码行数:25,代码来源:WebUrlRead.cs

示例4: GetUrlHtml

        /// <summary>
        /// 读取指定Url的Html源代码
        /// </summary>
        /// <param name="sUrl">指定Url</param>
        /// <param name="sEncoding">指定读取编码</param>
        /// <returns></returns>
        public static string GetUrlHtml(string sUrl, string encoding)
        {
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(sUrl);
            Req.Referer = UrlHelper._referer;
            Req.Method = "GET";
            Req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1;)";
            Req.AllowAutoRedirect = true;
            Req.MaximumAutomaticRedirections = 10;
            // 超时时间30000=30秒
            Req.Timeout = 10000;
            //  是否建立TCP持久连接
            Req.KeepAlive = false;

            HttpWebResponse response = (HttpWebResponse)Req.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding myEncoding = Encoding.GetEncoding(encoding);
            StreamReader streamReader = new StreamReader(stream, myEncoding);
            string html = streamReader.ReadToEnd();
            streamReader.Close();
            streamReader.Dispose();
            stream.Close();
            stream.Dispose();
            response.Close();

            return html;
        }
开发者ID:nienianjun,项目名称:dtz,代码行数:32,代码来源:UrlHelper.cs

示例5: SetDebug

        /// <summary>
        /// 设置调试
        /// </summary>
        /// <param name="isDebug"></param>
        internal static void SetDebug(bool isDebug)
        {
            string content = String.Empty;
            bool isChange = false;

            using (StreamReader fs = new StreamReader(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory)))
            {
                content = fs.ReadToEnd();
                fs.Dispose();
            }

            Regex reg = new Regex("<compilation([^(debug)])+debug=\"([^\"]+)\"", RegexOptions.IgnoreCase);
            if (reg.IsMatch(content))
            {
                Match m = reg.Match(content);
                if ((m.Groups[2].Value == "true" && !isDebug) || (m.Groups[2].Value == "false" && isDebug))
                {
                    content = reg.Replace(content, String.Format("<compilation$1debug=\"{0}\"", isDebug ? "true" : "false"));
                    isChange = true;
                }
            }

            if (isChange)
            {
                using (FileStream fs = new FileStream(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory),
                    FileMode.Truncate, FileAccess.Write,FileShare.ReadWrite))
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Dispose();
                }
            }
        }
开发者ID:AntonWong,项目名称:cms,代码行数:38,代码来源:WebConfig.cs

示例6: GetMatches

 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="pattern"></param>
 /// <returns></returns>
 public static MatchCollection GetMatches(string fileName, string pattern)
 {
     StreamReader reader = null;
     MatchCollection collection = null;
     try
     {
         reader = new StreamReader(fileName);
         string fileText;
         lock (new object())
         {
             using (reader)
             {
                 fileText = reader.ReadToEnd();
             }
         }
         collection = GetMatchesFromString(fileText, pattern);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.ToString());
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
             reader.Dispose();
         }
     }
     return collection;
 }
开发者ID:liorg,项目名称:SnappySinppetMerge,代码行数:37,代码来源:Util.cs

示例7: EngineInit

        /// <summary>Load engine resourses (models, interface, etc)</summary>
        void EngineInit()
        {
            // READ SETUP FILE
            StreamReader setupFile = null;
            try
            {
                setupFile = new StreamReader(Settings.dir + "\\setup");
            }
            catch
            {
                Settings.TerminateWindow(Settings.dir + "\nNie można odczytać pliku konfiguracyjnego 'setup'");
            }
            string line;
            while( (line = setupFile.ReadLine()) != null )
            {
                string[] args = line.Split(' ');
                switch( args[0] )
                {
                    case "self":	// user position
                        positionCamera.X = float.Parse(args[1], CultureInfo.InvariantCulture);
                        positionCamera.Y = float.Parse(args[2], CultureInfo.InvariantCulture);
                        positionCamera.Z = float.Parse(args[3], CultureInfo.InvariantCulture);
                        break;
                }
            }

            // clean
            setupFile.Dispose();
        }
开发者ID:Twigg92,项目名称:CrimeanCrisis,代码行数:30,代码来源:game_init.cs

示例8: Post

        public void Post(UserSocialConnection ConnectionData, string Update)
        {
            try
            {
                string apiCallUrl = String.Format("https://graph.facebook.com/me/feed"); // Format the call string
                HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(apiCallUrl);
                wr.Method = "POST";
                wr.ContentType = "application/x-www-form-urlencoded";

                string data = "access_token=" + ConnectionData.Token + "&message=" + HttpUtility.UrlEncode(Update);
                wr.ContentLength = data.Length;
                StreamWriter sw = new StreamWriter(wr.GetRequestStream());
                sw.Write(data);
                sw.Close();

                StreamReader sr = new StreamReader(wr.GetResponse().GetResponseStream());
                string jsonResponse = sr.ReadToEnd();

                sr.Close();

                sw.Dispose();
                sr.Dispose();

                if (jsonResponse.Contains("\"error_code\"")) // Proces the response for errors - a simple throw is used to convert the text error in to an exception
                    throw new Exception(String.Format("Error calling facebook API!\nJSON: {0} \nAPI CALL: {1}", jsonResponse, apiCallUrl));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception occurred in FacebookSocialConnector.Post processing User ID #" + ConnectionData.UserId + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
开发者ID:bscarlavai,项目名称:social-gamer,代码行数:31,代码来源:FacebookSocialConnector.cs

示例9: ReadFileAsString

 public static string ReadFileAsString(string filePath)
 {
     if (File.Exists(filePath))
     {
         string result = string.Empty;
         StreamReader sr = null;
         try
         {
             sr = new StreamReader(filePath, Encoding.UTF8);
             result = sr.ReadToEnd();
         }
         catch
         {
             result = string.Empty;
         }
         finally
         {
             sr.Close();
             sr.Dispose();
         }
         return result;
     }
     else
         return string.Empty;
 }
开发者ID:jmptrader,项目名称:SuperSocket.FtpServer,代码行数:25,代码来源:FileHelper.cs

示例10: OutOptionsTest

        public void OutOptionsTest()
        {
            MemoryStream memStream = new MemoryStream();
            StreamWriter writer = new StreamWriter(memStream);
            writer.AutoFlush = true;
            InstallerLog.AddWriter(writer, InstallerLog.DefaultLineFormat);

            String line = "test";
            InstallerLog.WriteLine(line);

            memStream.Position = 0;
            StreamReader reader = new StreamReader(memStream);
            Assert.AreEqual(line, reader.ReadLine(), "DefaultLineFormat should only write the line itself.");

            memStream.Position = 0;
            InstallerLog.RemoveWriter(writer, false);
            InstallerLog.AddWriter(writer, InstallerLog.TimeStampedLineFormat);
            InstallerLog.WriteLine(line);

            memStream.Position = 0;
            String expectedLine = String.Format(InstallerLog.TimeStampedLineFormat, line, DateTime.Now.ToString());
            Assert.AreEqual(expectedLine, reader.ReadLine(), "TimeStampLineFormat should include timestamp.");

            writer.Dispose();
            reader.Dispose();
        }
开发者ID:Pjanssen,项目名称:ScriptCenter,代码行数:26,代码来源:InstallerLogTest.cs

示例11: Main

        private static void Main(string[] args)
        {
            StreamReader reader = new StreamReader("../../wordFile.txt");
             StreamReader readerSearchFile = new StreamReader("../../textFile.txt");
             StreamWriter writer = new StreamWriter("../../resultFile.txt");
            try
            {

                SortedDictionary<String, int> words = new SortedDictionary<string, int>();
                string word = reader.ReadLine();
                string textFile = readerSearchFile.ReadToEnd().ToLower();
                while (word != null)
                {
                    word = word.ToLower();

                    string pattern = @"\b" + word + @"\b";
                    MatchCollection matches = Regex.Matches(textFile, pattern);
                    words.Add(word, matches.Count);
                    word = reader.ReadLine();

                }
                var ordered = words.OrderByDescending(pair => pair.Value);
                foreach (KeyValuePair<string, int> pair in ordered)
                {
                    writer.WriteLine("{0} - {1}", pair.Key, pair.Value);
                }
            }
            finally
            {
                writer.Flush();
                reader.Dispose();
                readerSearchFile.Dispose();
                writer.Dispose();
            }
        }
开发者ID:exploitx3,项目名称:C-Sharp-,代码行数:35,代码来源:Word+Count.cs

示例12: HttpRequest

        /// <summary>
        /// Http Post(utf-8编码)
        /// </summary>
        /// <param name="parms">请求参数</param>
        /// <returns>请求结果</returns>
        public static string HttpRequest(string parms)
        {
            string result = String.Empty;
            try
            {
                byte[] postData = Encoding.UTF8.GetBytes(parms);
                //old:http://124.42.83.34:8080/greatwallweb/main
                //new:http://124.42.83.34:9191/greatwallweb/main
                //official http://218.28.234.14:8080/greatwallweb/main
                //HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://218.28.234.14:8080/greatwallweb/main");
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://124.42.83.34:8080/greatwallweb/main");
                webRequest.Timeout = 30000;
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = postData.Length;

                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(postData, 0, postData.Length);
                requestStream.Close();
                requestStream.Dispose();
                StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();
            }
            catch { }
            return result;
        }
开发者ID:caocf,项目名称:workspace-kepler,代码行数:33,代码来源:Common.cs

示例13: CreateHTMLFromXMLFile

		public String CreateHTMLFromXMLFile (String SourceFileName, string identifier)
			{
			if (!File.Exists (SourceFileName))
				{
				WMB.Basics.ReportErrorToEventViewer ("XMLToHTML.CreateHTMLFromXMLFile","Beim Erzeugen des HTML Files fehlte der File \"" + SourceFileName +"\"");
				return String.Empty;
				}

			try
				{
				StreamReader reader = new StreamReader (SourceFileName, Encoding.UTF8);
				string str = reader.ReadToEnd ();
				reader.Close ();
				reader.Dispose ();

				CreateHTMLString (str, identifier);
				}
			catch (Exception Excp)
				{
				WMB.Basics.ReportErrorToEventViewer ("XMLToHTML.CreateHTMLFromXMLFile","Beim Erzeugen des HTML Files aus dem File \"" + SourceFileName +"\" trat folgender Fehler auf:\r\n"+ Excp.ToString());
				return String.Empty;
				}

			return CreatedHTMLResult;
			}
开发者ID:heinzsack,项目名称:DEV,代码行数:25,代码来源:XMLToHTMLHelper.cs

示例14: HttpWebRequestUsage

        public HttpWebRequestUsage()
        {
            lock (_lock)
            {
                DataSet ds = new DataSet();

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://219.146.59.6:38000/MONITOR_WEB/servlet/QueryTerminalOnlineTime?starttime=" );
                request.Timeout = 50000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();
                StreamReader readStream = new StreamReader(resStream);

                XmlDocument d = new XmlDocument();
                d.Load(readStream);
                d.Save("a.xml");
                ds.ReadXml("a.xml");

                // Close the stream object.
                resStream.Close();

                resStream.Dispose();
                readStream.Close();
                readStream.Dispose();

                // Release the HttpWebResponse.
                response.Close();
            }
        }
开发者ID:haisapan,项目名称:GoerTekLover,代码行数:28,代码来源:HttpWebRequestUsage.cs

示例15: Read

 public static string Read(string path)
 {
     FileStream fs = null;
     StreamReader sr = null;
     try
     {
         fs = File.OpenRead(path);
         sr = new StreamReader(fs);
         string content = sr.ReadToEnd();
         content = ClearValue(content);
         return content;
     }
     catch (Exception)
     {
         throw;
     }
     finally
     {
         if (sr != null)
         {
             sr.Dispose();
         }
         if (fs != null)
         {
             fs.Dispose();
         }
     }
 }
开发者ID:dalinhuang,项目名称:tdcodes,代码行数:28,代码来源:FileUtility.cs


注:本文中的System.IO.StreamReader.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。