473,396 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

C# LogAMessage class

109 100+
Hey guys.
I would like to build a class that i can use to log some messages into a textfile for easier web debugging.
so i guess my question is:
How do you direct output of a string into a textfile.

thank you
Apr 1 '08 #1
11 906
Plater
7,872 Expert 4TB
Look at the System.IO namespace. Thjere is the File, FileInfo, FileStream, StreamWriter(this one in particular probably) and the StreamReader can all help you.
Apr 1 '08 #2
Frinavale
9,735 Expert Mod 8TB
Hey guys.
I would like to build a class that i can use to log some messages into a textfile for easier web debugging.
so i guess my question is:
How do you direct output of a string into a textfile.

thank you
Check out the System.IO.File class for information on how to write files.

The example they list in that link is quite easy to follow (I've posted it below)
Expand|Select|Wrap|Line Numbers
  1.  string path = @"c:\temp\MyTest.txt";
  2.         if (!File.Exists(path)) 
  3.         {
  4.             // Create a file to write to.
  5.             using (StreamWriter sw = File.CreateText(path)) 
  6.             {
  7.                 sw.WriteLine("Hello");
  8.                 sw.WriteLine("And");
  9.                 sw.WriteLine("Welcome");
  10.             }    
  11.         }
  12.  
  13.         // Open the file to read from.
  14.         using (StreamReader sr = File.OpenText(path)) 
  15.         {
  16.             string s = "";
  17.             while ((s = sr.ReadLine()) != null) 
  18.             {
  19.                 Console.WriteLine(s);
  20.             }
  21.         }
  22.  
  23.         try 
  24.         {
  25.             string path2 = path + "temp";
  26.             // Ensure that the target does not exist.
  27.             File.Delete(path2);
  28.  
  29.             // Copy the file.
  30.             File.Copy(path, path2);
  31.             Console.WriteLine("{0} was copied to {1}.", path, path2);
  32.  
  33.             // Delete the newly created file.
  34.             File.Delete(path2);
  35.             Console.WriteLine("{0} was successfully deleted.", path2);
  36.         } 
  37.         catch (Exception e) 
  38.         {
  39.             Console.WriteLine("The process failed: {0}", e.ToString());
  40.         }
  41.     }
-Frinny
Apr 1 '08 #3
SpecialKay
109 100+
very nice, thank you.
However, it is eazy to follow im not quite sure how to modify it to my needs.
I want to append a message to a text file, without creating a new file every time.

is there a way that i could do:

file.open(path);
file.write(message '\n');
Apr 1 '08 #4
Plater
7,872 Expert 4TB
very nice, thank you.
However, it is eazy to follow im not quite sure how to modify it to my needs.
I want to append a message to a text file, without creating a new file every time.

is there a way that i could do:

file.open(path);
file.write(message '\n');
Look at the overloads to File.Open(), there are some choices there for append and such.
Apr 1 '08 #5
SpecialKay
109 100+
do you know what the options are for FileMode?
Apr 1 '08 #6
SpecialKay
109 100+
never mind, stupid question.
Do i need to make a FileStream? what is that?
or should i be able to just file.open?

it also seems like it only wants to accept a byte[]. If i have a simple string, how do i change that?
Apr 1 '08 #7
Plater
7,872 Expert 4TB
You can create a StreamWriter with a FileStream.
StreamWriter's constructor can take in a stream (FileStream is a stream) so you can use a StreamWriter instead.
Apr 1 '08 #8
SpecialKay
109 100+
Thank you, for your help.
Im still lost, but let me play around for a little bit. I will post another question in due time
Apr 1 '08 #9
SpecialKay
109 100+
if you could give me some code to try that would be great, lets say i have a string message = "I like Cheese";

and i want to have a class, with a function that will send that string to a text file. My code so far (Not working):

Expand|Select|Wrap|Line Numbers
  1. public class LogAMessage
  2. {
  3.     string path = @"\\server\test.txt";
  4.     public LogAMessage()
  5.     {
  6.         //
  7.         // TODO: Add constructor logic here
  8.         //
  9.     }
  10.     public static void logAMessage(string message)
  11.     {
  12.         try
  13.         {
  14.             FileStream s2 = new FileStream(path, FileMode.Append, FileAccess.Write);
  15.             s2.Write(message, 0, message.Length);
  16.         }
  17.         catch (Exception ex)
  18.         {
  19.             throw ex;
  20.         }
  21.     }
  22.  
Apr 1 '08 #10
Plater
7,872 Expert 4TB
Need an extra little step
Expand|Select|Wrap|Line Numbers
  1. public static void logAMessage(string message)
  2.     {
  3.         try
  4.         {
  5.             FileStream s2 = new FileStream(path, FileMode.Append, FileAccess.Write);
  6.             StreamWriter sw = new StreamWriter(s2);
  7.             sw.Write(message);
  8.         }
  9.         catch (Exception ex)
  10.         {
  11.             throw ex;
  12.         }
  13.     }
  14.  
Apr 1 '08 #11
SpecialKay
109 100+
logfile.txt gets created, but is empty

Expand|Select|Wrap|Line Numbers
  1.     public static void logAMessage(string message)
  2.     {
  3.         string path = "c:\\logfile.txt";
  4.         try
  5.         {
  6.             FileStream s2 = new FileStream(path, FileMode.Append);
  7.             StreamWriter sw = new StreamWriter(s2);
  8.             sw.Write(DateTime.Now);
  9.             sw.Write(" :: ");
  10.             sw.Write(message);
  11.         }
  12.         catch (Exception ex)
  13.         {
  14.             throw ex;
  15.         }
  16.  
Apr 1 '08 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Murat Tasan | last post by:
hi, i am having a small problem with constructing an inner class. i am using an inner class (and not a static nested class) because the methods of the inner class need access to the enclosing...
2
by: Fernando Rodriguez | last post by:
Hi, I need to traverse the methods defined in a class and its superclasses. This is the code I'm using: # An instance of class B should be able to check all the methods defined in B #and A,...
2
by: Gabriel Genellina | last post by:
Hi In the following code sample, I have: - a Worker class, which could have a lot of methods and attributes. In particular, it has a 'bar' attribute. This class can be modified as needed. - a...
3
by: Robert | last post by:
Python doesn't know the class of a method when container not direct class attribute: >>> class X: .... def f():pass .... g=f .... l= .... >>> X.g <unbound method X.f>
1
by: Oplec | last post by:
Hi, I'm learning C++ as a hobby using The C++ Programming Language : Special Edition by Bjarne Stroustrup. I'm working on chpater 13 exercises that deal with templates. Exercise 13.9 asks for me...
9
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class...
5
by: Andy | last post by:
Hi all, I have a site with the following architecture: Common.Web.dll - Contains a CommonPageBase class which inherits System.Web.UI.Page myadd.dll - Contains PageBase which inherits...
3
by: Hamilton Woods | last post by:
Diehards, I developed a template matrix class back around 1992 using Borland C++ 4.5 (ancestor of C++ Builder) and haven't touched it until a few days ago. I pulled it from the freezer and...
0
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.