• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# StreamReader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中StreamReader的典型用法代码示例。如果您正苦于以下问题:C# StreamReader类的具体用法?C# StreamReader怎么用?C# StreamReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: ConcatTwoFiles

 static void ConcatTwoFiles(string firstFileName, string secondFileName)
 {
     /*Write a program that compares two text files line by line and prints the number of lines that are
       the same and the number of lines that are different. Assume the files have equal number of lines.*/
     int sameLines = 0;
     int differentLines = 0;
     using (StreamReader readFirstFile = new StreamReader(firstFileName))
     {
         using (StreamReader readSecondFile = new StreamReader(secondFileName))
         {
             string lineFirstFile = readFirstFile.ReadLine();
             string lineSecondFile = readSecondFile.ReadLine();
             while (lineFirstFile != null && lineSecondFile != null)
             {
                 if (lineFirstFile == lineSecondFile)
                 {
                     sameLines++;
                 }
                 else
                 {
                     differentLines++;
                 }
                 lineFirstFile = readFirstFile.ReadLine();
                 lineSecondFile = readSecondFile.ReadLine();
             }
         }
     }
     Console.WriteLine("The number of lines that are the same: {0}", sameLines);
     Console.WriteLine("The number of lines that are different: {0}", differentLines);
 }
开发者ID:Jarolim,项目名称:HomeWork,代码行数:30,代码来源:4.Compare2filesSameLines.cs


示例2: Main

 static void Main()
 {
     var readerOne = new StreamReader("test.txt", Encoding.GetEncoding("Windows-1251"));
     var readerTwo = new StreamReader("test2.txt", Encoding.GetEncoding("Windows-1251"));
     using (readerOne)
     {
         int sameCount = 0;
         int differentCount = 0;
         string lineOne = readerOne.ReadLine();
         using (readerTwo)
         {
             string lineTwo = readerTwo.ReadLine();
             while (lineOne != null)
             {
                 if (lineOne == lineTwo)
                 {
                     sameCount++;
                 }
                 else
                 {
                     differentCount++;
                 }
                 lineOne = readerOne.ReadLine();
                 lineTwo = readerTwo.ReadLine();
             }
             Console.WriteLine("The same lines are {0} and the different lines are {1}",sameCount,differentCount);
         }
     }
 }
开发者ID:AYankova,项目名称:Telerik-Academy-HW,代码行数:29,代码来源:04.+Compare+text+files.cs


示例3: ReplaceTarget

    public static void ReplaceTarget(List<string> words)
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            using (StreamWriter writer = new StreamWriter("temp.txt"))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(@"\b(");
                foreach (string word in words) sb.Append(word + "|");

                sb.Remove(sb.Length - 1, 1);
                sb.Append(@")\b");

                string pattern = @sb.ToString();
                Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                for (string line; (line = reader.ReadLine()) != null; )
                {
                    string newLine = rgx.Replace(line, "");
                    writer.WriteLine(newLine);
                }
            }
        }

        File.Delete("test.txt");
        File.Move("temp.txt", "test.txt");
    }
开发者ID:Rokata,项目名称:TelerikAcademy,代码行数:27,代码来源:RemoveWords.cs


示例4: Main

 static void Main()
 {
     try
     {
         StreamReader reader = new StreamReader(@"D:\newfile.txt");
         List<string> newText = new List<string>();
         using (reader)
         {
             string line = reader.ReadLine();
             int lineNumber = 0;
             while (line != null)
             {
                 lineNumber++;
                 newText.Add(lineNumber.ToString() + ". " + line);
                 line = reader.ReadLine();
             }
         }
         StreamWriter writer = new StreamWriter(File.Open(@"D:\ResultIs.txt",FileMode.Create));
         using (writer)
         {
             for (int i = 0; i < newText.Count; i++)
             {
                 writer.WriteLine(newText[i]);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
开发者ID:RamiAmaire,项目名称:TelerikAcademy,代码行数:32,代码来源:ReadFileAndInsertLineNum.cs


示例5: Main

    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");
        List<string> info = new List<string>();

        using (reader)
        {
            string line = reader.ReadLine();
            while (line != null)
            {
                int i = 0;
                while (i < line.Length - 1)
                {
                    if ((line.IndexOf('>', i) != -1)
                        && (line.IndexOf('>', i) != line.Length - 1)
                        && (line.IndexOf('<', line.IndexOf('>', i)) != line.IndexOf('>', i) + 1))
                    {
                        info.Add(line.Substring(line.IndexOf('>', i) + 1,
                            line.IndexOf('<', line.IndexOf('>', i)) - 1 - line.IndexOf('>', i)));
                        i = line.IndexOf('<', line.IndexOf('>', i)) + 1;
                    }
                    else
                    {
                        i++;
                    }
                }
                line = reader.ReadLine();
            }
        }
        Console.WriteLine(string.Join(",", info));
    }
开发者ID:zvet80,项目名称:TelerikAcademyHomework,代码行数:31,代码来源:ExtractTextFromXML.cs


示例6: CountWords

    //Write a program that reads a list of words from a file words.txt and finds how many times 
    //each of the words is contained in another file test.txt. The result should be written in 
    //the file result.txt and the words should be sorted by the number of their occurrences in 
    //descending order. Handle all possible exceptions in your methods.

    private static Dictionary<string, int> CountWords(string inputPath, string listOfWordsPath)
    {
        List<string> list = ExtractList(listOfWordsPath);
        StreamReader reader = new StreamReader(inputPath);
        Dictionary<string, int> result = new Dictionary<string, int>();

        using (reader)
        {
            while (reader.Peek() != -1)
            {
                string currline = reader.ReadLine();

                for (int i = 0; i < list.Count; i++)
                {
                    Regex word = new Regex("\\b" + list[i] + "\\b");

                    foreach (Match match in word.Matches(currline))
                    {
                        //for each word met, if already met - increase counter, else - start counting it
                        if (result.ContainsKey(list[i]))
                        {
                            result[list[i]]++;
                        }
                        else
                        {
                            result.Add(list[i], 1);
                        }
                    }
                }
            }
        }
        return result;
    }
开发者ID:Varbanov,项目名称:TelerikAcademy,代码行数:38,代码来源:CountSomeWordsInFile.cs


示例7: Main

 static void Main()
 {
     using (StreamReader input = new StreamReader("../../1.txt"))
         using (StreamWriter output = new StreamWriter("../../2.txt"))
             for (string line; (line = input.ReadLine()) != null; )
                 output.WriteLine(line.Replace("start", "finish"));
 }
开发者ID:martinangelos88,项目名称:CSharpProject,代码行数:7,代码来源:7.ReplaceSubString1To2.cs


示例8: Main

    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\input.txt");

        List<string> allEvenLines = new List<string>();

        string currLine = null;

        while (1 == 1)
        {
            currLine = reader.ReadLine();//Line1 (1/3/5/7)
            currLine = reader.ReadLine();//Line2 (4/6/8/10)
            if (currLine == null)
            {
                break;
            }
            allEvenLines.Add(currLine);
        }
        reader.Close();

        StreamWriter writer = new StreamWriter(@"..\..\input.txt", false); // after closing the reader
        foreach (string line in allEvenLines)
        {
            writer.WriteLine(line);
        }
        writer.Close();
    }
开发者ID:purlantov,项目名称:TelerikAcademy-4,代码行数:27,代码来源:09.+DeleteAllOddLines.cs


示例9: Main

    static void Main()
    {
        StreamReader reader = new StreamReader(@"..\..\practice.txt");
        StringBuilder builder = new StringBuilder();

        using (reader)
        {
            string line = reader.ReadLine();
            int lineIndex = 0;

            while (line != null)
            {
                lineIndex++;
                builder.AppendLine(string.Format("{0}. {1}", lineIndex, line));
                line = reader.ReadLine();
            }
        }

        StreamWriter writer = new StreamWriter(@"..\..\result.txt");

        using (writer)
        {
            writer.Write(builder.ToString());
        }
    }
开发者ID:hiksa,项目名称:Telerik-Academy,代码行数:25,代码来源:InsertLineNumbers.cs


示例10: Main

 static void Main()
 {
     StreamReader reader1 = new StreamReader("../../file1.txt");
     StreamReader reader2 = new StreamReader("../../file2.txt");
     string line1 = reader1.ReadLine();
     string line2 = reader2.ReadLine();
     int sameCount = 0;
     int totalCount = 0;
     while (line1 != null) // * Assume the files have equal number of lines.
     {
         if (line1 == line2)
         {
             sameCount++;
         }
         Console.WriteLine("{0} ?= {1} -> {2}", line1, line2, line1 == line2);
         line1 = reader1.ReadLine();
         line2 = reader2.ReadLine();
         totalCount++;
     }
     reader1.Close();
     reader2.Close();
     Console.WriteLine(new string('=', 25));
     Console.WriteLine("Identic lines: {0}", sameCount);
     Console.WriteLine("Different lines: {0}", totalCount - sameCount);
 }
开发者ID:tima-t,项目名称:Telerik-Academy,代码行数:25,代码来源:Program.cs


示例11: Main

    static void Main()
    {
        var reader = new StreamReader("..\\..\\input.txt");
        string[] input = reader.ReadToEnd().Split(' ');
        reader.Close();
        string deletedWord = "start";
        string newWord = "finish";
        for (int i = 0; i < input.Length; i++)
        {
            if (input[i]==deletedWord)
            {
                input[i] = newWord;
            }
        }
        string result = string.Join(" ", input);
        var writer = new StreamWriter("..\\..\\result.txt");
        using (writer)
        {
            if (result != null)
            {
                writer.WriteLine(result);
            }

        }
    }
开发者ID:DanteSparda,项目名称:TelerikAcademy,代码行数:25,代码来源:Program.cs


示例12: SameWordsSequences

 public static Dictionary<string, int> SameWordsSequences(List<string> words)
 {
     using (StreamReader InputFileTest = new StreamReader("..//..//InputFileTest.txt"))
     {
         Dictionary<string, int> dictionary = new Dictionary<string, int>();
         string line = InputFileTest.ReadLine();
         while (line != null)
         {
             string[] wordsOnLine = line.ToLower().Split(' ', '.', ';', ':');
             foreach (string word in wordsOnLine)
             {
                 if (words.Contains(word))
                 {
                     if (!dictionary.ContainsKey(word))
                     {
                         dictionary.Add(word, 1);
                     }
                     else ++dictionary[word];
                 }
             }
             line = InputFileTest.ReadLine();
         }
         return dictionary;
     }
 }
开发者ID:danielkaradaliev,项目名称:TelerikAcademyAssignments,代码行数:25,代码来源:Count.cs


示例13: LoadContain

    public string LoadContain()
    {
        if (Request.QueryString["CourseId"] == null)
        {
            return string.Empty;
        }

        string ThePath = string.Empty;
        string RetData = string.Empty;
        using (OleDbConnection Con = new OleDbConnection(constr))
        {
            OleDbCommand cmd = new OleDbCommand(String.Format("SELECT TOP 1 DataPath FROM CoursenotimeDataPath WHERE CourseId = {0}", Request.QueryString["CourseId"]), Con);
            try
            {
                Con.Open();
                ThePath = cmd.ExecuteScalar().ToString();
                //if (ThePath != string.Empty)
                //    ThePath = MapPath(DB.CourseNoTimeFileDir + ThePath);
                ThePath = DB.CourseNoTimeFileDir + ThePath;

                TextReader TR = new StreamReader(ThePath);
                RetData = TR.ReadToEnd();
                TR.Close();
                TR.Dispose();

            }
            catch (Exception ex)
            {
                RetData = ex.Message;
            }
            Con.Close();
        }

        return HttpUtility.HtmlDecode(RetData);
    }
开发者ID:EgyFalseX,项目名称:WebSites,代码行数:35,代码来源:ViewCourseNoTimeDetailsViewer.ascx.cs


示例14: Deserialize

 public object Deserialize(
     StreamReader streamReader, 
     SerializationContext serializationContext, 
     PropertyMetaData propertyMetaData = null)
 {
     return streamReader.ReadInt16();
 }
开发者ID:gordonc64,项目名称:AOtomation.Messaging,代码行数:7,代码来源:Int16Serializer.cs


示例15: Main

    static void Main()
    {
        string textOne = "";
        string textTwo = "";
        try
        {
            StreamReader reader = new StreamReader(@"../../FirstTextFile.txt");
            using (reader)
            {
                textOne = reader.ReadToEnd();
            }

            reader = new StreamReader(@"../../SecondTextFile.txt");
            using (reader)
            {
                textTwo = reader.ReadToEnd();
            }

            ConcatenateTwoStrings(textOne, textTwo);
        }
        catch
        {
            Console.WriteLine("Something went wrong! Check file paths or file contents.");
        }
    }
开发者ID:NikolovNikolay,项目名称:Telerik-Homeworks,代码行数:25,代码来源:ConcatenateTwoInOne.cs


示例16: Main

    static void Main()
    {
        Console.WriteLine("Enter the full path of the text file");
          string path = Console.ReadLine();
          StreamReader reader = new StreamReader(path);

          StreamWriter writer = new StreamWriter("text.txt", false, Encoding.GetEncoding("windows-1251"));
          List<string> list = new List<string>();

        using (writer)
        {
            using(reader)
            {
                string line = reader.ReadLine();

                    while(line!=null)
                {
                    list.Add(line);
                    line = reader.ReadLine();
                }

                    list.Sort();
            }

            foreach (string s in list)
            {
                writer.WriteLine(s);
            }
        }
    }
开发者ID:huuuskyyy,项目名称:CSharp-Homeworks,代码行数:30,代码来源:Program.cs


示例17: PostStream

	static string PostStream (Mono.Security.Protocol.Tls.SecurityProtocolType protocol, string url, byte[] buffer)
	{
		Uri uri = new Uri (url);
		string post = "POST " + uri.AbsolutePath + " HTTP/1.0\r\n";
		post += "Content-Type: application/x-www-form-urlencoded\r\n";
		post += "Content-Length: " + (buffer.Length + 5).ToString () + "\r\n";
		post += "Host: " + uri.Host + "\r\n\r\n";
		post += "TEST=";
		byte[] bytes = Encoding.Default.GetBytes (post);

		IPHostEntry host = Dns.Resolve (uri.Host);
		IPAddress ip = host.AddressList [0];
		Socket socket = new Socket (ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
		socket.Connect (new IPEndPoint (ip, uri.Port));
		NetworkStream ns = new NetworkStream (socket, false);
		SslClientStream ssl = new SslClientStream (ns, uri.Host, false, protocol);
		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);

		ssl.Write (bytes, 0, bytes.Length);
		ssl.Write (buffer, 0, buffer.Length);
		ssl.Flush ();

		StreamReader reader = new StreamReader (ssl, Encoding.UTF8);
		string result = reader.ReadToEnd ();
		int start = result.IndexOf ("\r\n\r\n") + 4;
		start = result.IndexOf ("\r\n\r\n") + 4;
		return result.Substring (start);
	}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:28,代码来源:postecho.cs


示例18: Request_POST

    static public string Request_POST(string rooturl, string param)
    {

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(rooturl);
        Encoding encoding = Encoding.UTF8;
        byte[] bs = Encoding.ASCII.GetBytes(param);
        string responseData = String.Empty;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bs.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(bs, 0, bs.Length);
            reqStream.Close();
        }
        using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                responseData = reader.ReadToEnd().ToString();
            }
            
        }

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(responseData);
        XmlElement root = doc.DocumentElement;
        return root.InnerText;

    }
开发者ID:ProjectCosin,项目名称:Sample.Client,代码行数:30,代码来源:RequestMgr.cs


示例19: Main

 static void Main()
 {
     string firstFilePath = @"../../First.txt";
     string secondFilePath = @"../../Second.txt";
     string resultPath = @"../../result.txt";
     StreamReader firstPart = new StreamReader(firstFilePath);
     StreamReader secondPart = new StreamReader(secondFilePath);
     StreamWriter result = new StreamWriter(resultPath);
     string lineOne = String.Empty;
     string lineTwo = String.Empty;
     string resultStr = String.Empty;
     using(firstPart)
     {
         lineOne = firstPart.ReadToEnd();
     }
     using (secondPart)
     {
         lineTwo = secondPart.ReadToEnd();
     }
     using (result)
     {
         resultStr = lineOne + "\r\n" + lineTwo;
         result.WriteLine(resultStr);
     }
 }
开发者ID:madbadPi,项目名称:TelerikAcademy,代码行数:25,代码来源:ConcatenateTextFiles.cs


示例20: Main

    static void Main()
    {
        // Reads some text file
        StreamReader read = new StreamReader("file.txt");
        using (read)
        {
            // Creates an empty list and fill it
            string line = read.ReadLine();
            List<string> list = new List<string>();
            for (int l = 0; line != null; l++)
            {
                // Adds each one word from the file in the list
                list.Add(line);

                // Reads the next line
                line = read.ReadLine();
            }

            // Sorting the list
            list.Sort();

            // Write the sorted list in some output file
            StreamWriter write = new StreamWriter("output.txt");
            using (write)
            {
                foreach (var word in list)
                {
                    write.WriteLine(word);
                }
            }
        }
    }
开发者ID:Termininja,项目名称:TelerikAcademy,代码行数:32,代码来源:ListOfStrings.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# StreamSequenceToken类代码示例发布时间:2022-05-24
下一篇:
C# StreamMode类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap