C#: File Operations

person Jason Huangfolder_openC#, Codelocal_offer, , access_time October 5, 2009

Here is some easy to use C# library functions:

Read Text File into String:

        private string ReadFileIntoString(string inputfile)
        {
            string theString = "";
            StreamReader reader = new StreamReader(inputfile);
            try
            {
                theString = reader.ReadToEnd();
            }
            finally
            {
                reader.Close();
            }
 
            return theString;
        }

Write Text String into File:

        public static void WriteTextFile(string sLogFileName, string sMessageLine)
        {
            System.IO.FileStream fs = new System.IO.FileStream(sLogFileName, System.IO.FileMode.OpenOrCreate,     System.IO.FileAccess.Write);
            System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
            m_streamWriter.WriteLine(sMessageLine);
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

Convert byte into MB, GB etc:

private static string ConvertByte(long lbyte, int type)
		{
			long lSize = 0;
			string unit = "";
 
			long lnBYTE = 1;
    	    long lnKILO = 1024; //					' 2^10
    		long lnMEGA = 1048576; //				' 2^20
    	    long lnGIGA = 1073741824; //			' 2^30
    		long lnTERA = 1099511627776; //			' 2^40
    	//'	Const lnPETA = 1.12589990684262E+15		' 2^50
    	//'	Const lnEXA = 1.15292150460685E+18		' 2^60
    	//'	Const lnZETTA = 1.18059162071741E+21	' 2^70
    	//'	Const lnYOTTA = 1.20892581961463E+24	' 2^80
 
			if (lbyte >0)
			{
				switch (type)
				{
					case 0: //kb
                        lSize = lbyte / lnKILO;
						unit = "KB";
						break;
					case 1: //mb
						lSize = lbyte / lnMEGA;
						unit = "MB";
						break;
					case 3: //gb
						lSize = lbyte / lnGIGA;
						unit = "GB";
						break;
				}
			}
 
			return lSize.ToString() + " " + unit;
		}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>