Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Example #1
1
        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();
            }
        }
Example #2
1
 /// 获取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;
 }
Example #3
1
 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;
     }
 }
Example #4
0
        /// <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;
        }
Example #5
0
        /// <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();
                }
            }
        }
Example #6
0
 /// <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;
 }
Example #7
0
        /// <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();
        }
        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);
            }
        }
 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;
 }
Example #10
0
        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();
        }
Example #11
0
        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();
            }
        }
Example #12
0
        /// <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;
        }
Example #13
0
		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;
			}
        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();
            }
        }
Example #15
0
 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();
         }
     }
 }
Example #16
0
        public static CsvDelimiter DetectFieldDelimiterChar(string filename, System.Text.Encoding encoding)
        {
            TextReader textReader = null;
            CsvDelimiter delimiter;

            try
            {
                textReader = new StreamReader(filename, encoding);
                delimiter = DetectFieldDelimiterChar(textReader.ReadLine());

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception occured in field delimiter detection routine: " + e.Message);
                delimiter = CsvDelimiter.Comma;
                throw;
            }
            finally
            {
                if (textReader != null)
                {
                    textReader.Close();
                    textReader.Dispose();
                }
            }

            return delimiter;
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();

            if (!storage.FileExists("LeaveSettings.xml"))
            {
                this.PayPeriodBase.Text = PayPeriodUtilities.GetCurrentPayPeriod().AddDays(-1).ToShortDateString();
                this.AnnualBalance.Focus();
            }
            else
            {
                using (storage)
                {
                    XElement _xml;
                    IsolatedStorageFileStream location = new IsolatedStorageFileStream(@"LeaveSettings.xml", System.IO.FileMode.Open, storage);
                    System.IO.StreamReader file = new System.IO.StreamReader(location);
                    _xml = XElement.Parse(file.ReadToEnd());
                    if (_xml.Name.LocalName != null)
                    {
                        this.AnnualBalance.Text = _xml.Attribute("AnnualBalance").Value;
                        this.SickBalance.Text = _xml.Attribute("SickBalance").Value;
                        this.AnnualAccrue.Text = _xml.Attribute("AnnualAccrue").Value;
                        this.SickAccrue.Text = _xml.Attribute("SickAccrue").Value;
                        this.PayPeriodBase.Text = _xml.Attribute("PayPeriod").Value;
                    }
                    file.Dispose();
                    location.Dispose();
                }
            }
        }
Example #18
0
        static public JadeData.Workspace.IWorkspace Read(string path)
        {
            WorkspaceType xml;
            XmlSerializer serializer = new XmlSerializer(typeof(WorkspaceType));
            TextReader tr = new StreamReader(path);
            try
            {                
                xml = (WorkspaceType)serializer.Deserialize(tr);                
            }
            finally
            {
                tr.Close();
                tr.Dispose();
            }

            JadeData.Workspace.IWorkspace result = new JadeData.Workspace.Workspace(xml.Name, path);

            foreach (FolderType f in xml.Folders)
            {
                result.AddFolder(MakeFolder(result.Directory, f));
            }
            foreach (ProjectType p in xml.Projects)
            {
                result.AddProject(MakeProject(result.Directory, p));
            }

            return result;
        }
Example #19
0
        /// <summary>
        /// 获取城市的天气状况
        /// </summary>
        /// <returns></returns>
        public static string GetWeather(string city)
        {
            string wUrl = string.Format("http://m.weather.com.cn/data/{0}.html", city);
            //string wUrl = @"http://m.weather.com.cn/data/101050101.html";
            HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create(wUrl);
            HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();

            wNetr.ContentType = "text/html";
            wNetr.Method = "Get";

            Stream Streams = wNetp.GetResponseStream();
            StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);

            String ReCode = Reads.ReadToEnd();
            //关闭暂时不适用的资源
            Reads.Dispose();
            Streams.Dispose();
            wNetp.Close();
            //分析返回代码
            String[] Splits = new String[] { "\"", ",", "\"" };
            String[] Temp = ReCode.Split(Splits, StringSplitOptions.RemoveEmptyEntries);
            string[] Temp1 = Temp[25].Split(new char[] { '~', '℃' });
            string[] Temp2 = Temp[28].Split(new char[] { '~', '℃' });
            string[] Temp3 = Temp[31].Split(new char[] { '~', '℃' });
            string[] Temp4 = Temp[34].Split(new char[] { '~', '℃' });
            string[] Temp5 = Temp[37].Split(new char[] { '~', '℃' });
            string[] Temp6 = Temp[40].Split(new char[] { '~', '℃' });
            ReCode = String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}", Temp1[0], Temp1[2], Temp2[0], Temp2[2], Temp3[0], Temp3[2], Temp4[0], Temp4[2], Temp5[0], Temp5[2], Temp6[0], Temp6[2]);

            return ReCode;
        }
Example #20
0
        public static string Render(string templateName, Dictionary<string, string> values)
        {
            if (File.Exists(TemplateDirectory + templateName + ".html"))
            {
                var sR = new StreamReader(File.OpenRead(TemplateDirectory + templateName + ".html"));

                string fileContent = sR.ReadToEnd();

                foreach (var d in values)
                {
                    fileContent = fileContent.Replace("{"+d.Key+"}",d.Value);
                }

                sR.Close();
                sR.Dispose();

                return fileContent;
            }
            else
            {
                Logger.LogError("Can't find template " + templateName);
            }

            return "";
        }
Example #21
0
         public string GetBusinessObject(string SystemCode, string BusinessObjectName)
        {
            string text = string.Empty;
            try
            {
                if (SystemCode == null || SystemCode == "" || BusinessObjectName == null || BusinessObjectName == "")
                    return null;
                var Path = ConfigurationManager.AppSettings["BOPath"];
                var BusinessObjectFolder = GetBusinessObjectFolder(Path, SystemCode);

                if (BusinessObjectFolder == null || BusinessObjectFolder == "")
                    return null;
                Path = Path + "\\" + BusinessObjectFolder + "\\" + BusinessObjectName + ".xml";
                Tracer.Debug("GetBusinessObject,filePath" + Path);
                if (!File.Exists(Path))
                    return null;
                StreamReader file = new StreamReader(Path);
                text = file.ReadToEnd();
                file.Close();
                file.Dispose();
            }
            catch (Exception ex)
            {
                Tracer.Debug(ex.ToString());
            }
           return text;
        }
Example #22
0
 public Site Get()
 {
     Site site = null;
     if (!File.Exists(file))
     {
         site = new Site
                        {
                            Title = "New Site",
                            Email = "[email protected]"
                        };
         Save(site);
         return site;
     }
     site  = null;
     StreamReader sr = null;
     try
     {
         sr = new StreamReader(file);
         var str = sr.ReadToEnd();
         var serializer = new JavaScriptSerializer();
         site = serializer.Deserialize<Site>(str);
     }
     finally
     {
         sr.Close();
         sr.Dispose();
         sr = null;
     }
     return site;
 }
Example #23
0
 public void CreateHtml(string temPath, Maticsoft.Model.CMS.Content model, string createPath)
 {
     string str = string.Empty;
     string str2 = string.Empty;
     try
     {
         str2 = HttpContext.Current.Server.MapPath(createPath);
         StreamReader reader = new StreamReader(System.IO.File.Open(HttpContext.Current.Server.MapPath(temPath), FileMode.Open, FileAccess.Read), Encoding.GetEncoding("utf-8"));
         StringBuilder builder = new StringBuilder(reader.ReadToEnd());
         reader.Close();
         reader.Dispose();
         string str4 = builder.ToString().Replace("$id$", model.ContentID.ToString()).Replace("$content$", model.Description);
         this.CreatFolder(createPath);
         str = "ContentDetail-" + model.ContentID + ".html";
         StreamWriter writer = new StreamWriter(System.IO.File.Create(str2 + "/" + str), Encoding.GetEncoding("utf-8"));
         writer.Write(str4);
         writer.Flush();
         writer.Close();
         writer.Dispose();
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #24
0
        public static string Post(string uri, Dictionary<string, string> postParameters)
        {
            string postData = "";
            foreach (string key in postParameters.Keys)
            {
                postData += HttpUtility.UrlEncode(key) + "="
                      + HttpUtility.UrlEncode(postParameters[key]) + "&";
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);

            string result = reader.ReadToEnd();
            stream.Dispose();
            reader.Dispose();
            return result;
        }
        private IDictionary<string, string> GetFileProperties()
        {
            if (!File.Exists(PROPERTIES_FILE))
                throw new Exception(String.Format("Configuration file {0} not found.", PROPERTIES_FILE));

            IDictionary<string, string> properties = new Dictionary<string, string>();
            List<String> lines = new List<string>();
            using (StreamReader reader = new StreamReader(PROPERTIES_FILE, Encoding.GetEncoding("ISO-8859-1")))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);
                }

                if (lines.Count > 0)
                {
                    String[] keyValues = lines.ToArray();
                    properties = keyValues.ToDictionary(
                        s => (!String.IsNullOrEmpty(s) && s.Split('=').Length > 0) ? s.Split('=')[0].Trim() : String.Empty,
                        s => (!String.IsNullOrEmpty(s) && s.Split('=').Length > 1) ? s.Split('=')[1].Trim() : String.Empty);
                }

                reader.Close();
                reader.Dispose();
            }

            return properties;
        }
Example #26
0
        protected string Read_Txt(string filename)
        {

            Encoding code = Encoding.GetEncoding("gb2312");
            string temp = HttpContext.Current.Server.MapPath("Precious\\" + filename + ".txt");
            string str = "";
            if (File.Exists(temp))
            {
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(temp, code);
                    str = sr.ReadToEnd(); // 读取文件
                }
                catch { }
                sr.Close();
                sr.Dispose();
            }
            else
            {
                str = "";
            }


            return str;
        }
 /// <summary>
 /// Serializes current XmlInterchange object into an XML string
 /// </summary>
 /// <returns>string XML value</returns>
 public virtual string Serialize(System.Text.Encoding encoding)
 {
     StreamReader streamReader = null;
     MemoryStream memoryStream = null;
     try
     {
         memoryStream = new MemoryStream();
         System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
         xmlWriterSettings.Encoding = encoding;
         xmlWriterSettings.Indent = true;
         System.Xml.XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings);
         Serializer.Serialize(xmlWriter, this);
         memoryStream.Seek(0, SeekOrigin.Begin);
         streamReader = new StreamReader(memoryStream, encoding);
         return streamReader.ReadToEnd();
     }
     finally
     {
         if ((streamReader != null))
         {
             streamReader.Dispose();
         }
         if ((memoryStream != null))
         {
             memoryStream.Dispose();
         }
     }
 }
Example #28
0
 static void Main(string[] args)
 {
     TextReader rdr = null;
     try {
         rdr = new StreamReader("Hello_Debug_Trace.txt");
         string s = rdr.ReadToEnd();
         Console.WriteLine(s);
     }
     catch (Exception ex)
     {
         Console.WriteLine("StreamReader: "+ex.Message);
     }
     finally
     {
         if (rdr != null)
         {
             rdr.Dispose();
         }
     }
     TextReader rdr1 = null;
     try {
         using (rdr1 = new StreamReader("Hello_Debug_Trace.txt"))
         {
             string s = rdr1.ReadToEnd();
             Console.WriteLine(s);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("StreamReader: " + ex.Message);
     }
 }
Example #29
0
        public static string ReadLog(DateTime filename)
        {

            Encoding code = Encoding.GetEncoding("gb2312");
            var dir = System.AppDomain.CurrentDomain.BaseDirectory + "\\Log\\";
            if (Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            string temp = dir + DateTime.Today.Date.ToString("yyyyMMdd") + ".txt"; //保存文件的路径
            string str = "";
            if (File.Exists(temp))
            {
                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(temp, code);
                    str = sr.ReadToEnd(); // 读取文件
                }
                catch { }
                sr.Close();
                sr.Dispose();
            }
            else
            {
                str = "";
            }


            return str;
        }
        protected void SetUp()
        {
            var f = new FileStream("config.json", FileMode.Open);
            var sr = new StreamReader(f);
            try
            {
                var settings = JsonConvert
                    .DeserializeObject<MongoSettings>(sr.ReadToEnd());
                var client = new MongoClient(new MongoUrl(settings.Url));
                _database = client.GetDatabase(settings.DatabaseName);
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Talk to John about why this one fails");
            }
            finally
            {
                f.Dispose();
                sr.Dispose();
            }

            _collectionName = Guid.NewGuid().ToString();
            _collection = _database.GetCollection<Container>(_collectionName);
            var mapper = new StringMapper<BasePaymentModel>(x => x.PaymentType)
                .Register<AchInputModel>("ach")
                .Register<CreditCardInputModel>("cc")
                .Register<PayPalInputModel>("paypal");
            BsonSerializer.RegisterDiscriminatorConvention(
                typeof(BasePaymentModel),
                new DiscriminatorConvention<string, BasePaymentModel>(mapper));
        }