Csharp/C Sharp/File Stream/StringWriter

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

The hex dump program.

 

using System;
using System.IO;

class Class1 {
    public static string Pad(string s, int len) {
        string temp = s;
        for (int i = s.Length; i < len; ++i)
            temp = "0" + temp;
        return temp;
    }
    static void Main(string[] args) {
        StreamReader sr = new StreamReader("c:\\a.txt");
        string line = "";
        int nCounter = 0;
        int nOffset = 0;
        while ((line = sr.ReadLine()) != null) {
            for (int i = 0; i < line.Length; ++i) {
                int c = (int)line[i];
                string fmt = String.Format("{0:x}", c);
                if (fmt.Length == 1)
                    fmt = Pad(fmt, 2);
                if (nOffset % 16 == 0) {
                    string offsetFmt = nOffset.ToString();
                    System.Console.Write(Pad(offsetFmt, 5) + ": ");
                }
                System.Console.Write(fmt + " ");
                if (nCounter == 15) {
                    System.Console.Write("\n");
                    nCounter = 0;
                } else
                    nCounter++;
                nOffset++;
            }
        }
    }
}


Use StringWriter to write string

using System;
using System.IO;
using System.Text;
class StringReadWriteApp {
    static void Main(string[] args) {
        StringWriter w = new StringWriter();
        w.WriteLine("Sing a song of {0} pence", 6);
        string s = "A pocket full of rye";
        w.Write(s);
        w.Write(w.NewLine);
        w.Write(String.Format(4 + " and " + 20 + " blackbirds"));
        w.Write(new StringBuilder(" baked in a pie"));
        w.WriteLine();
        w.Close();
        Console.WriteLine(w);
    }
}