By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,642 Members | 1,474 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,642 IT Pros & Developers. It's quick & easy.

Efficient way to write to a text file and append?

P: 1
I am familiar with two ways of writing to a text file so the data persists when you access it again. Adding more data (from textbox and label) will be necessary for future transactions. I'd like to learn how to write the code so I don't get an UnauthorizedAccessException class.

I am using this way, resulting in error:

Expand|Select|Wrap|Line Numbers
  1. Dim objwriter As New System.IO.StreamWriter("C:\Customer Transactions.txt")
  2.  
  3.         objwriter.Write(txtCustName.Text, lblOrderNo, lblFinalCost)
  4.         objwriter.Close()

And there is this way (with errors again):
Expand|Select|Wrap|Line Numbers
  1.   Dim myStream As Stream
  2.         Dim saveFileDialg As New SaveFileDialog()
  3.  
  4.         saveFileDialg.Filter = ("C:\Customer Transactions.txt")
  5.         saveFileDialg.FilterIndex = 2
  6.         saveFileDialg.RestoreDirectory = True
  7.  
  8.         If saveFileDialg.ShowDialog() = DialogResult.OK Then
  9.             myStream = saveFileDialg.OpenFile()
  10.             If (myStream IsNot Nothing) Then
  11.                 myStream.WriteLine(txtFullName.Text, lblOrder, lblTotal)
  12.                 myStream.Close()
  13.                 myStream.Close()
  14.             End If
  15.         End If

I'm sure there is something I am not quite getting. Some guidance would be appreciated.
Dec 16 '13 #1
Share this Question
Share on Google+
1 Reply


Frinavale
Expert Mod 5K+
P: 9,731
The Windows user that is running your application does not have permissions to create files on C:\. You need administrative privileges to change any files in the C:\ root directory.

Try writing the file into the application's executing path instead. For information about getting the application's path check out this article
[url=http://msdn.microsoft.com/en-us/library/aa457089.aspx]
HOW TO: Determine the Executing Application's Path[/icode].

You could also consider writing into the ProgramData path (for example you could try using C:\ProgramData\YourApplicationName).

-Frinny
Dec 17 '13 #2

Post your reply

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