1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development C# exporting to .txt

Discussion in 'Software' started by liratheal, 2 Aug 2010.

  1. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    I have had a look through google, but that's proving to be slightly fruitless as I seem to want to do something different.

    I do a lot of server checks for work, and I email the results of these tests, so the issues can be dealt with by anyone with a few moments spare.

    I got rather bored with retyping the client names and so on on a regular basis, so I thought;

    Why not write a C# app to give me a checkbox for backup and a/v check confirmation, a box for each of them detail wise, and an "other" box for any additional issues unrelated to the above. Then, have a button so I can export that information to a .txt file, so when I'm done with the checks I can copy/paste the txt contents into the email and be done with it.

    Essentially, the app would auto-fill the client name (selected from a drop down menu), then if the checkboxs are marked drag the data from the appropriate text box, and export it to a .txt file, that's named with the days date or something.

    So, I'd have the app as such;

    [​IMG]

    and the text file as;

    [​IMG]

    I'm fairly certain I can muddle through doing the if statements for which boxes to extract data from, and when 'export' is clicked to clear the checkboxes, the text boxes, and the selected client. What I don't know is how to export it to a .txt with the days date (dd-mm-yy) and have them all, so long as the date doesn't change, export to the same .txt, just adding to the existing list if it's already there.

    Any help would be greatly appreciated!
     
  2. mjb501

    mjb501 What's a Dremel?

    Joined:
    20 Jun 2010
    Posts:
    37
    Likes Received:
    7
    Hey, you want something like this:

    Code:
    string filename;
    filename = DateTime.Now.Date.ToShortDateString();
    filename = filename.Replace("/","-");
    filename += ".txt";
    
    TextWriter writer;
    if (File.Exists(filename))
    {
        writer = File.AppendText(filename);
    }
    else
    {
        writer = File.CreateText(filename);
    }
    
    This get the current date and converts it to a string, it then removes the backslashes and replaces them with a dahes.

    It then checks to see if the file already exists at the location given by the filename, if it does any text you write using the writer will be appended at the end of the text file.

    If not it will create a new file with the filename and then write the text to it.

    Hope that helps.
     
    liratheal likes this.
  3. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    That's excellent, thank you.
     
  4. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    Just be sure to delimit it properly, either with a special character (pipe character, perhaps) or with padded spaces. The latter is a bit harder.
    Reason for me saying that is that it makes it easier to import into, say, excel later on if that should be needed.
     
  5. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    It'll only ever be going into an email, copy/paste style.

    Essentially it's so I don't have to type 60+ names five times a week, when I'd really rather be doing something more productive :p
     
  6. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    I am sure there's a bulti in copy/paste in .NET somewhere... never thought of it, but ca't see it not being the case.
     
  7. capnPedro

    capnPedro Hacker. Maker. Engineer.

    Joined:
    11 Apr 2007
    Posts:
    4,381
    Likes Received:
    241
    Clipboard.SetText( string );

    It's a piece of piss with the Clipboard class.
     
  8. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    I knew there was a way. .NET makes it all so very easy... I love it for that. :)
     
  9. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    It sounds nifty, but I've got to do ~60 of these checks, I'd rather copy/paste one large block rather than 60 little ones :p
     
  10. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    makes sense, I suppose...
    But I am sure there's a way to optimise further... you'll stumble upon it once the app is done and functioning... That's the way development normally goes.
     
  11. mjb501

    mjb501 What's a Dremel?

    Joined:
    20 Jun 2010
    Posts:
    37
    Likes Received:
    7
    Your right, there is!

    You could get C# to create and send the email for you!
    I have had a poke around MSDN and .Net has classes for creating and sending emails from your appliation.

    You will need to use the System.Net.Mail namespace to get access to the classes.
    http://msdn.microsoft.com/en-us/library/system.net.mail.aspx

    This is a pretty basic bit so smaple code that shows you how to send an email from a C# program.
    http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx

    This is a sample program from MS on how to create a simple email program.
    http://code.msdn.microsoft.com/nclsamples/Wiki/View.aspx?title=Mailer

    If you can get that working it could save you having to copy & paste from a text file, so even less boring work to do!
     
  12. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    Right, I'm struggling again.

    I abandoned the initial plan to grab text based on whether there was a checkbox or not, partly because I realised I get asked if any not mentioned checks are okay or not, and partly because it boggled me >.>

    I can't seem to get it to pull the text from any boxes, even using plain old

    Code:
    File.WriteAllText("c:\\test.txt", txtBackup.Text);
    Thoughts?

    For what it's worth, I'm probably just missing something blindingly obvious, but I'm no coder :p
     
  13. mjb501

    mjb501 What's a Dremel?

    Joined:
    20 Jun 2010
    Posts:
    37
    Likes Received:
    7
    When you have finished writing all the text do you call writer.Flush()?

    So for your code above you'd want to do this:

    Code:
    TextWriter writer;
    writer = File.WriteAllText("c:\\test.txt", txtBackup.Text);
    writer.Flush();
    The flush method is the bit that actually writes the text to the file.
     
  14. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    Was about to mention Flush().
    It caught me out every time for a while... until it got drilled into my skull.... :)
     
  15. mjb501

    mjb501 What's a Dremel?

    Joined:
    20 Jun 2010
    Posts:
    37
    Likes Received:
    7
    I got caught out as well!

    Although I did find that you can do it like this as well:

    Code:
                using (TextWriter streamWriter = File.CreateText(filename))
                {
                    streamWriter.WriteLine("nn");
                }
    The using cleans up the TextWriter automatically when the code within the braces has been executed, mean it call Flush() automatically!

    http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx
     
    Last edited: 3 Aug 2010
  16. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    I must be going mental.

    Code:
            public static void btnExport_Click(object sender, EventArgs e)
            {
                    TextWriter writer;
                    writer = File.AppendAllText("c:\\serverchecks.txt", txtBackup.Text);
                    writer.Flush();
    
                //string filename;
                //filename = DateTime.Now.Date.ToShortDateString();
                //filename = filename.Replace("/", "-");
                //filename += ".txt";
    
                //TextWriter writer;
                //if (File.Exists(filename))
                //{
                //    writer = File.AppendText(filename);
                //}
                //else
                //{
                //    writer = File.CreateText(filename);
                //}
            }
    That's the "Export" button code, however, it's erroring and claiming that "an object reference is required for the non-static field" referring to "txtBackup".

    I am royally confused. Perhaps this was a bit of an ambitious project for my first non-guided C# experience >.>
     
  17. mjb501

    mjb501 What's a Dremel?

    Joined:
    20 Jun 2010
    Posts:
    37
    Likes Received:
    7
    I get a different Error message when I try the code you posted:

    "Cannot implicitly convert type 'void' to 'System.IO.TextWriter"

    Which is because File.AppendAllText("",""); does not return a stream writer.

    If you alter the code to this it should work:

    Code:
    public static void btnExport_Click(object sender, EventArgs e)
            {
                    TextWriter writer;
                    writer = [B]File.AppendText("c:\\serverchecks.txt");
                    writer.WriteLine(txtBackup.Text);[/B]
                    writer.Flush();
            }
    Basically, it calls File.AppendText instead of File.AppendAllText (int bold) which just takes a filename instead of a filename and the text to write.

    Then you write the text from the text box to the file using writer.WriteLine.
     
  18. yakyb

    yakyb i hate the person above me

    Joined:
    10 Oct 2006
    Posts:
    2,064
    Likes Received:
    36
    Code:
     
     var Lines = new List<string>{"hello","World"};
     var f = new FileStream(@"C:\File.txt", FileMode.Append);
    
    using (var writer = new StreamWriter(f))
     {
             foreach (var L in Lines)
            {
                   writer.WriteLine(L);
             }
    }
     
    this is an excerpt from a simple logging class that eventually emails me the content
     
  19. liratheal

    liratheal Sharing is Caring

    Joined:
    20 Nov 2005
    Posts:
    12,864
    Likes Received:
    1,968
    I bet you thought you'd got rid of me, but no! I'm back :p

    I ended up starting from scratch, as there was so much code floating around commented out I felt like a fresh start.

    Miracles occurred, and everything worked first time, but the second click of "export" provided;

    The process cannot access the file 'c:\users\xcon\documents\visual studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\09-08-2010.txt' because it is being used by another process.

    Code:
            private void btnExport_Click(object sender, EventArgs e)
            {
                string filename;
                filename = DateTime.Now.Date.ToShortDateString();
                filename = filename.Replace("/", "-");
                filename += ".txt";
    
                TextWriter writer;
                if (File.Exists(filename))
                {
                    writer = File.AppendText(filename);
                    writer.WriteLine(cmbClients.Text);
                    writer.WriteLine(txtBack.Text);
                    writer.WriteLine(txtAV.Text);
                    writer.WriteLine(txtOther.Text);
                    writer.Flush();
                }
                else
                {
                    writer = File.CreateText(filename);
                    writer.WriteLine(cmbClients.Text);
                    writer.WriteLine(txtBack.Text);
                    writer.WriteLine(txtAV.Text);
                    writer.WriteLine(txtOther.Text);
                    writer.Flush();
                }
            }
    That's the "export" code, which is working nicely for the first export;

    Code:
    DBK Man
    dfsdfsdfdvbsdhg
    A/V: Fine
    Other: Fine
    
    I'm guessing it's not closing the .txt properly with the .flush part, thoughts?
     
  20. capnPedro

    capnPedro Hacker. Maker. Engineer.

    Joined:
    11 Apr 2007
    Posts:
    4,381
    Likes Received:
    241
    If you're going to reopen your filestream for every write, stick writer.Close(); after the flush line.
     

Share This Page