Writing to text file

Hi all! Using VB 2008.

I need to write to a text file. Create and write if it does not exist
or append if it does. I have this code:

    If System.IO.File.Exists("G:\work\temp\TestTxtFiles\Box\testfile.txt") 
Then
      'Open file for append.
      Using oFile As System.IO.StreamWriter = 
System.IO.File.AppendText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
        oFile.WriteLine("Test file line 4")
        oFile.WriteLine("Test file line 5")
        oFile.WriteLine("Test file line 6")
        oFile.Close()
      End Using
    Else
      'Create a test text file.
      Using oFile As System.IO.StreamWriter = 
System.IO.File.CreateText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
        oFile.WriteLine("Table CODES")
        oFile.WriteLine("Test file line 1")
        oFile.WriteLine("Test file line 2")
        oFile.WriteLine("Test file line 3")
        oFile.Close()
      End Using
    End If

It works. My question is whether this is the best way to do this or if there 
is
a more optimized method. Thanks! Saga


0
Saga
3/1/2010 10:50:30 PM
dotnet.languages.vb 830 articles. 0 followers. Follow

2 Replies
1224 Views

Similar Articles

[PageSpeed] 11

On 3/1/2010 5:50 PM, Saga wrote:
> Hi all! Using VB 2008.
>
> I need to write to a text file. Create and write if it does not exist
> or append if it does. I have this code:
>
>      If System.IO.File.Exists("G:\work\temp\TestTxtFiles\Box\testfile.txt")
> Then
>        'Open file for append.
>        Using oFile As System.IO.StreamWriter =
> System.IO.File.AppendText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
>          oFile.WriteLine("Test file line 4")
>          oFile.WriteLine("Test file line 5")
>          oFile.WriteLine("Test file line 6")
>          oFile.Close()
>        End Using
>      Else
>        'Create a test text file.
>        Using oFile As System.IO.StreamWriter =
> System.IO.File.CreateText("G:\work\temp\TestTxtFiles\Box\testfile.txt")
>          oFile.WriteLine("Table CODES")
>          oFile.WriteLine("Test file line 1")
>          oFile.WriteLine("Test file line 2")
>          oFile.WriteLine("Test file line 3")
>          oFile.Close()
>        End Using
>      End If
>
> It works. My question is whether this is the best way to do this or if there
> is
> a more optimized method. Thanks! Saga
>
>

AppendText creates the file if it is not found, so you don't need the 
check, nor two branches.  Just use AppendText and skip the CreateText 
routine.

-- 
Mike
0
Family
3/1/2010 11:10:06 PM
> AppendText creates the file if it is not found, so you don't need the 
> check, nor two branches.  Just use AppendText and skip the CreateText 
> routine.
>
Thanks for the tip, much appreciated! I will make the corresponding change
to my code. Saga

> -- 
> Mike 


0
Saga
3/2/2010 5:53:35 PM
Reply:

Similar Artilces:

Extract phone number front block of text
I have a webpage that lists business names, address, phone number, etc. There is no definite pattern to how they entered the text. What I' like to do is something like.... -Search cell A1 for "-", return the 3 characters to the left of th "-".- In the next column do... -Search cell A1 for "-", return the 4 characters to the right of th "-".- Then I can concatenate the two and add in the area code. TIA guys/gals. PS. I tried searching but didn't know exactly what to search for an didn't get very far -- Tec ------------------------...

cycle through n files
I've got a series of operations to do on n excel files the directory is the same..the names of the files are 0001..0002...0003...0004..until 0067 How can I do that through a macro?? Hi I have examples here http://www.rondebruin.nl/tips.htm If you need help post back -- Regards Ron de Bruin http://www.rondebruin.nl "Rossella" <rossy77@gmail.com> wrote in message news:1144840532.042950.93010@i39g2000cwa.googlegroups.com... > I've got a series of operations to do on n excel files > the directory is the same..the names of the files are > 0001..0002...0003.....

when i upgraded my files disapeared
i was using the beta for office 2003 and it expired on november30. i went out and bought 2003pro and tried to install it. the beta said that it needed to be uninstalled before i could install the full version. the beta didnt let me back up any information and when i uninstalled it it took all of its info and settings with it. i lost all contacts emails and settings. is there any i can get those back? >the beta said that it needed to be >uninstalled before i could install the full version. the >beta didnt let me back up any information and when i >uninstalled it it took all ...

outlook.pst file repair tool?
how to repair outlook.pst file which may be corrupted Monis Beraha <anonymous@discussions.microsoft.com> wrote: > how to repair outlook.pst file which may be corrupted Search your HD for scanpst.exe -- Brian Tillman ...

Make Excel upload files via FTP??
A few days ago I asked about creating files from a Excel worksheet that can be shared online. Someone suggested this VBA: http://www.meadinkent.co.uk/xladvhtml.htm I've been trying this and it works. Now I want to get Excel to run the VBA-code every time the file is closed, AND (and now comes the tricky part), to upload the created html-files to a FTP account. Every time the file is closed the macro "make_htm" should run, and get the files got created upload from the local folder, to a FTP account. Is this possible?? ...

How to read binary file created by non-MFC source?
I am a newbie working on a simple project for loading a binary file and displaying its byte-by-byte contents in interger equivalent. The file was created by some unknown source (presummably not MFC). I am using SDI/CScrollView interface and the file is supposed to be open under FILE/OPEN menu. At the beginning, I've been trying to include CString str; ar >> str; in void CMyProjectDoc::Serialize(CArchive &ar) as an attempt to put everything in str prior to converting every byte into interger. What happened was 1) The first byte (which is known to be a 92) was missing; and 2) ...

I want a round invitation for a wedding shower with circle text
The invitation I found is a circle, with the invite going around the outside edge of the circle and more information inside that circle and it is also circular. It has a flower and brad in the middle. The instructions for it simply say, type text on computer, make circular by using WordArt feature. My computer is running on Vista operating system. I have a sample WordArt circle here http://msauer.mvps.org/wordart_in_microsoft_publisher.htm Scroll way down. -- Mary Sauer MVP http://msauer.mvps.org/ "Kay-Kay" <Kay-Kay@discussions.microsoft.com> wrote i...

How to copy a field of A excel file to B Excel file automatically?
I need to copy some fields of A.xls to B.xls every night at 12:00. how can I do that? I'd try one of two methods. First, use the MS Windows "scheduler" to fire off you spreadsheet at midnight (make sure to leave the computer turned on) and have a VBA macro triggered when the workbook is opened to perform the data movement. A second, albeit more difficult method, would be to write VBA code to structure an internal timer that would watch for midnight. In this case, you'd have to open the workbook before going home for the day, and activate the macro that sets ...

Need to extrcat data from one Excel file to an other
Hi there I'm looking form a solution to press on button in a Excel sheet which ill exctract some datas from an other Excel sheet which can be close or opened. It should beworing on Windows XP, 2003, Vista and 7 as well with 32 bits and 64 bits. Thanks in avance for your advise and best regards Tra Browse through the example codes found at Ron de Bruin's site. http://www.rondebruin.nl/tips.htm Look at the 'Copy/paste/merge" section. Should be some good material to start with. Gord Dibben MS Excel MVP On Sat, 28 May 2011 19:53:03 +0200, Tra Sumaka <trasumak...

Exporting an editable file
I don't have Publisher Have a (luddite) client who has a two page .pub document and after a struggle, finally got it in pdf format, but the pdf does not allow copying any of the text although the security settings allow it. How do I tell her to export the text so that it can be included in an information document? Thanks, Beverly Howard Will copy and paste into Word do it for you? -- Don Vancouver, USA "Beverly Howard [Ms-MVP/MobileDev]" <BevNoSpamBevHoward.com> wrote in message news:uVIla2EoEHA.3792@TK2MSFTNGP11.phx.gbl... > I don't have Publisher > &...

deleting files / freeing space
When I delete files by hilighting, pressing delete then emptying the recycle bin ----- no space actually gets cleared up When i delete by holding shift + delete ---- space does free up I'm running: XP Home Version 2002 SP3 I'm not crazy or a newbie but am an MCTS and have never seen this before in all my years ghostsniper007 wrote: > When I delete files by hilighting, pressing delete then emptying the > recycle bin ----- no space actually gets cleared up > > When i delete by holding shift + delete ---- space does free up > > I'm running: XP Ho...

File Extensions
I've lost all emails and attachments from O. E. after upgrading to Windows XP and Office XP. I can't find a list of file extensions for Express in any help. Anyone know these extensions? Thanks Hi - they're .dbx files. But note - This is a group to support Outlook from the Office group of programs. Outlook Express is a part of Internet Explorer and is a quite different program, despite its similar name.. You will probably get a faster and more expert answer if you post this to an Outlook Express news group. Try posting in one of these newsgroups: microsoft.public.windows.ine...

CtreeCtrl & item.iIntegral with manifest file not working correctly
Hi I working on a project and the tree items have different heights, i am changing the height with item.iIntegral see TVITEMEX Structure. Thats working perfect but if apply my application the manifest file for XP-Style see http://www.codeproject.com/macro/vc-xp.asp The tree lines are broken, is there a work around? If i remove the manifest files the tree control is working perfect.I want to use the XP-Style but also have the TreeCtrl working, any idea? I hope somebody can help me.... bye bye Lorenz Test Code i am using : m_tree is an CTreeCtrl; First call fillTree after that unequ...

Issue with CSV file
I am programmatically creating a CSV file that has a list of formulae from a workbook/worksheet (see example below). Note that there are 5 records in the file, tho the text might wrap below in your newsreader to appear to have more lines. Double clicking on the CSV file causes Excel to issue #NAME? errors for the records marked as BAD, The records marked as "BAD" cause Excel to try to update the text due to the included references to worksheets. This occurs for a formula that begin with a "-" character. And, ditto for a "+". I can avoid the problem by sticking an...

On replies & forwards
When I reply to an email, it uses annoying blue text. I can't see anyplace that I can turn that off. I have Outlook 2000. Does anyone know something about how to stop this annoying behavior? Regards, Alan Easy fix--Tools, Options, Mail Format tab, Fonts, Select Fonts. Select your font, color for reply or anything else. "Alan B." wrote: > When I reply to an email, it uses annoying blue text. I can't see anyplace > that I can turn that off. I have Outlook 2000. Does anyone know something > about how to stop this annoying behavior? > > Regards, > A...

how do I convert pagemaker files to publisher
Can publisher convert adabe pagemaker files? Nope! "Judy J" <Judy J@discussions.microsoft.com> wrote in message news:F1C2F61A-464B-4E71-806E-ED3290B6A2BD@microsoft.com... > Can publisher convert adabe pagemaker files? ...

text in Bullets/points in cell
How can one write the text in bullets or points in the cell in excel 2007. Hold the ALT key, then on the NUMERIC KEYPAD, type 0149, then let go of the ALT key -- you'll have your bullet •<== works here, too! "kamal" wrote: > How can one write the text in bullets or points in the cell in excel 2007. ...

Corrupt Money file appears to create system instability
Looking for some help and assistance correcting an apparently corrupt Money file that results in my laptop rebooting when I have Money open (but not immediately on open). Worked with MS support to try file repair (level 2 fails), then selectively deleted the accounts that appeared to cause problem (Amex and Schwab). Repair files executes successfully when accounts are deleted. Trouble is, I need them, and have been using Money as my personal finance software since 2001. 1) Is this a known problem? 2) Is is related to Money 2006, that I upgraded to 2 weeks ago? 3) How can I fix it? ...

How to I convert text to curves in Microsoft Publisher?
You can't. This is a feature normally found in draw applications rather than DTP applications. -- Ed Bennett - MVP Microsoft Publisher http://ed.mvps.org Michael, you can put text into Word Art, make it look like normal text by choosing a basic style and then you can shape it with Word Art shapes. It won't be practical for long text but for titles and stuff it works terrific. -- Katmido University of Delaware "Ed Bennett" wrote: > You can't. This is a feature normally found in draw applications rather > than DTP applications. > > -- > Ed Benn...

Convert text to date 12-21-07
Hello, I am trying to link to a text file. I was having trouble converting 20011975 into a date/time format but it wasn't working. So I formatted the field as a text file. I have tried converting this to 20/01/1975 in a query but it comes out with errors and wierd dates. I've had a look at the other messages and had a go but no go. thanks Regardless of how your dates are displayed either by formatting or based on regional settings, all date functions exppect a month day year format. To convert your string to a date field: strTextDate = "20011975" SomeDate = DateSer...

How to file compare Excel worksheets
I add records, daily, to a master file. Sometimes a record is a duplicate. At this point, I sort by one column and then scroll down looking for duplicate records, which I delete. Is there an easier way? I don't want to have duplicate records. THanks, Walt What I usually do is in a new column put: =IF(AND(A2=A1),"DUP","") This only works if you are trying to compare a column with unique IDs. However, if you're looking at a list of names where some names might be duplicated (example: Two people named James, but one lives in USA and the other lives in Germ...

Linking formulas to text boxes in VBA
Hi, I just posted this to the programmers section, but I think those folks are into more serious things than this! I'm newly experimenting with VBA, so apologies if this is a stupid question. Any help much appreciated! I have a For - Next loop that creates a formula linking a cell in an 'input sheet' ("Key") to a cell in any one of 200 sheets. For cells, this is no problem, using: For i = 1 to 200 Worksheets(i).Range("c2").Formula = "=Key!B" & i Next i My problem comes when I try to do the same with some text boxes that are in each of the 200 s...

Corrupted local file hyperlinks in Excel 2007
Anyone know what would cause a hyperlink in the form of c:\folder\folder2\filename.ext to convert to Documents%20and%20Settings/myname/application%20Data/Microsoft/Excel/folder/folder2/filename.ext ? Excel 2007 has damaged all my hyperlinks and I've had to edit them all to restore them all manually. (find/replace won't look at hyperlinks). System: XP Pro, Service Pack 3.0, Office 2007. A few people have said that this has stopped a similar problem from occurring. Maybe it'll help you--but you'll have to test it to make sure. In xl2003 menus: File|Prop...

Delete file in "most recent used" section
I have two files that I have moved on my computer. Now whenever I load excel it tells me that a file is missing, and the "open a workbook" section contains two files which no longer exist. How can I delete these from "open workbook". When I click on them, obviously Excel can't locate them. Thanks Click on Tools....Options....clear the recently used file list....click on Okay. The history should be cleared. Repeat steps to have that feature return. "Scott" wrote: > I have two files that I have moved on my computer. Now whenever I load excel >...

How to add text to all existing records in one column?
Hi Friends, I have another question to ask. I had this problem many times - and do not know how to solve it. Ok: I have a column with information on patients blood samples, such as: RA3453 ST RA4322 TA I have to add "OCT" to each record in this column in most simple way (there are 18.000 records). The result for these samples should be like this: OCT RA3453 ST OCT RA4322 TA Thanks in advance Daniel (usmleboy) If your data always starts with RA, then select the column Edit|Replace what: RA with: OCT RA replace all. If your prefix varies, I'd use another column and fill...