tags:

views:

367

answers:

4

This is a WinForm written in C#. Lets say I'm generating a random named text file in my selected directory. When the button is clicked teh first time, i write the data contained in the textboxes into that text file. If the user wants to do the same thing with different data in the textboxes then the click on the button should write the new data into the text file without losing the old data. It's like keeping logs, is this possible?

My code is like:

private readonly Random setere = new Random(); 
    private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    private string RandomString() 
    { 
        char[] buffer = new char[5]; 
        for (int i = 0; i < 5; i++) 
        { 
            buffer[i] = chars[setere.Next(chars.Length)]; 
        } 
        return new string(buffer); 
    }




    private void button1_Click(object sender, EventArgs e)
    {


        DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);


        if (dia == DialogResult.Yes)
        {
            StreamWriter wFile = new StreamWriter("C:\\Users\\Ece\\Documents\\Testings\\" + RandomString() + ".txt");
            wFile.WriteLine("Name Surname:" + text1.Text + text2.Text);
            wFile.WriteLine("Other:" + text3.Text + text4.Text);
            wFile.WriteLine("Money:" + textBox1.Text + " TL.");
            wFile.WriteLine("*************************************");
            wFile.Close();



        }
        else 
        {

            return;
        }


    }
+6  A: 

You can append to the text in the file.

See

File.AppendText

using (StreamWriter sw = File.AppendText(pathofFile)) 
        {
            sw.WriteLine("This");
            sw.WriteLine("is Extra");
            sw.WriteLine("Text");
        }

where pathofFile is the path to the file to append to.

rahul
A: 

Sure. Just open the file for appending with something like System.IO.File.AppendText

Adam Wright
+2  A: 

Have a look at using something like this:

StreamWriter fw = new StreamWriter(@"C:\Logs\MyFile.txt",true);
fw.WriteLine("Some Message" + Environment.Newline);
fw.Flush();
fw.Close();

Hope that helps. See MSDN StreamWriter for more information

Updated: Removed old example

Also if you are trying to create a unique file you can use Path.GetRandomFileName() Again from the MSDN Books:

The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name.

UPDATED: Added a Logger class example below

Add a new class to your project and add the following lines (this is 3.0 type syntax so you may have to adjust if creating a 2.0 version)

using System;
using System.IO;

namespace LogProvider
{
    //
    // Example Logger Class
    //
    public class Logging
    {
        public static string LogDir { get; set; }
        public static string LogFile { get; set; }
        private static readonly Random setere = new Random();
        private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        public Logging() {
            LogDir = null;
            LogFile = null;
        }

        public static string RandomFileName()
        {
            char[] buffer = new char[5];
            for (int i = 0; i < 5; i++)
            {
                buffer[i] = chars[setere.Next(chars.Length)];
            }
            return new string(buffer);
        }


        public static void AddLog(String msg)
        {
            String tstamp = Convert.ToString(DateTime.Now.Day) + "/" +
                            Convert.ToString(DateTime.Now.Month) + "/" +
                            Convert.ToString(DateTime.Now.Year) + " " +
                            Convert.ToString(DateTime.Now.Hour) + ":" +
                            Convert.ToString(DateTime.Now.Minute) + ":" +
                            Convert.ToString(DateTime.Now.Second);

            if(LogDir == null || LogFile == null) 
            {
               throw new ArgumentException("Null arguments supplied");
            }

            String logFile = LogDir + "\\" + LogFile;
            String rmsg = tstamp + "," + msg;

            StreamWriter sw = new StreamWriter(logFile, true);
            sw.WriteLine(rmsg);
            sw.Flush();
            sw.Close();
        }
    }
}

Add this to your forms onload event

LogProvider.Logging.LogDir = "C:\\Users\\Ece\\Documents\\Testings";
LogProvider.Logging.LogFile = LogProvider.Logging.RandomFileName();

Now adjust your button click event to be like the following:

DialogResult dia = MessageBox.Show("Wanna continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dia == DialogResult.Yes)
{
    StringBuilder logMsg = new StringBuilder();
    logMsg.Append("Name Surname:" + text1.Text + text2.Text + Environment.NewLine);
    logMsg.Append("Other:" + text3.Text + text4.Text + Environment.NewLine);
    logMsg.Append("Money:" + textBox1.Text + " TL." + Environment.NewLine);
    logMsg.Append("*************************************" + Environment.NewLine);
    LogProvider.Logging.AddLog(logMsg.ToString());
} else
{
    return;
}

Now you should only create one file for the entire time that application is running and will log to that one file every time you click your button.

Wayne
I didnt use GetRandomFileName since i was required to write a method myself.. Also I didnt get what TRUE changed, it still creates multiple files instead of writing in the one text file..
Lady Sour
Thats because of the way you are creating your filename. If you are after only 1 file then only create a unique file the FIRST time.
Wayne
+1  A: 

You might want to take a look at log4net and the RollingFileAppender

Mel Gerats