Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Go Back  Xtreme Visual Basic Talk > > > Saving a NEW text file each time the program runs


Reply
 
Thread Tools Display Modes
  #1  
Old 01-21-2013, 08:35 AM
jamietax jamietax is offline
Newcomer
 
Join Date: Jan 2013
Posts: 5
Default Saving a NEW text file each time the program runs


I have developed a program to test the influence of feedback on students. Throughout the program students answer questions and complete tasks that are then saved to a text file. Below is an example of the first time something is written into a text file.
Code:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim oFile As System.IO.File Dim oWrite As System.IO.StreamWriter oWrite = oFile.CreateText("C:\VB Material\data\participant.txt") oWrite.WriteLine("Condition = 1") oWrite.Close()
The text file is then appended in other forms with the following code.
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Age As String Age = txbAge.Text Dim oFile As System.IO.File Dim oWrite As System.IO.StreamWriter oWrite = oFile.AppendText("C:\VB Material\data\participant.txt") oWrite.Write("Age = ") oWrite.WriteLine(Age) If female.Checked = True Then oWrite.WriteLine("Gender = Female") End If If male.Checked = True Then oWrite.WriteLine("Gender = Male") End If Dim Grade As String Grade = txbGrade.Text oWrite.Write("Grade = ") oWrite.WriteLine(Grade) If rbgym.Checked = True Then oWrite.WriteLine("School = Gymnasium") End If If rbreal.Checked = True Then oWrite.WriteLine("School = Realschule") End If If rbhaupt.Checked = True Then oWrite.WriteLine("School = Hauptschule") End If oWrite.Close()
Right now the text file is rewritten each time the program runs. Is there a way to save a new text file each time instead?

Last edited by Gruff; 01-21-2013 at 10:23 AM.
Reply With Quote
  #2  
Old 01-21-2013, 10:20 AM
Gruff's Avatar
GruffSaving a NEW text file each time the program runs Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

Welcome to the forum Jamie, Do not forget to read the forum Posting Guidelines.

1) Another way to do this would be to take the some of the information information the student entered and create a unique filename. For example.

John Doe~CoolSchool~Beginning Algebra~2013-5-24~14-45.txt

2) I guess I would add a button and only save the data to the file when the Student presses this button. Perhaps a small screen would pop up with all the entries shown.
As a verification that all data is correct. <Press Yes if correct or No if not.>

3) Have you thought about using a database to hold all your infomation instead? Most schools use a database of some sort, not text files.
__________________
Burn the land and boil the sea
You can't take the sky from me


~T

Last edited by Gruff; 01-21-2013 at 10:27 AM.
Reply With Quote
  #3  
Old 01-21-2013, 10:56 AM
surfR2911 surfR2911 is offline
Contributor
 
Join Date: Oct 2009
Posts: 719
Default AppendText working sample

Quote:
Originally Posted by Gruff
Have you thought about using a database to hold all your infomation instead?
I agree with Gruff's suggestion, but if you want a working sample of AppendText you'll find one for download on this page.

Note: There is also a File.AppendAllText method that can be used as well.
Reply With Quote
  #4  
Old 01-22-2013, 03:38 AM
jamietax jamietax is offline
Newcomer
 
Join Date: Jan 2013
Posts: 5
Default

Thanks, but none of these options work for me.

1. The files have to be saved anonymously because this is an experiment where I manipulate feedback and see how it influences students.

2. Due to the reasons above the students are also not supposed to know where or how their data is being saved.

3. The program is going to be used at multiple schools so I don't think a database would work, but I am not really sure.

Also, appending the text is not my problem. That works fine. I just need to know if there is a way to automatically save the text file under a different name each time the program runs.

Last edited by jamietax; 01-22-2013 at 04:15 AM.
Reply With Quote
  #5  
Old 01-22-2013, 04:13 AM
jamietax jamietax is offline
Newcomer
 
Join Date: Jan 2013
Posts: 5
Default

I tried something along the lines that you mentioned and it is a step in the right direction, but still doesn't completely work. Below is the code that I used for the first time something is supposed to be written into a text file in the program.

Code:
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click    
  
Dim counter As System.Collections.ObjectModel.ReadOnlyCollection(Of String)    
counter = My.Computer.FileSystem.GetFiles("C:\VB Material\data\")    
  
Dim Filename As String    
  
Filename = "C:\VB Material\data\participant" & CStr(counter.Count) & ".txt"    
  
  
Dim oFile As System.IO.File    
Dim oWrite As System.IO.StreamWriter    
oWrite = oFile.CreateText(Filename)    
oWrite.WriteLine("Condition = 1")    
oWrite.Close()    
  
Me.Hide()    
Demo.Show()    
  
End Sub
So this, code created a text file saved as participant0.txt. But now my problem is that in the next form I need to append to the participant0.txt, but I am not able to do this because the variable 'Filename' is not declared on this form, but I can't declare it without reinitializing the file counter and I don't want 20 text files per participant, just one. I hope this makes sense.

My goal is to have one text file per person that completes the program. The program takes 20 minutes to go through and multiple things are appended to the text file throughout the program.
Reply With Quote
  #6  
Old 01-22-2013, 06:20 AM
DrPunk's Avatar
DrPunkSaving a NEW text file each time the program runs DrPunk is offline
Senior Contributor

* Expert *
 
Join Date: Apr 2003
Location: Never where I want to be
Posts: 1,403
Default

Quote:
Originally Posted by jamietax View Post
So this, code created a text file saved as participant0.txt. But now my problem is that in the next form I need to append to the participant0.txt, but I am not able to do this because the variable 'Filename' is not declared on this form, but I can't declare it without reinitializing the file counter and I don't want 20 text files per participant, just one. I hope this makes sense.
You could declare the variable globally.

Another way of tackling the problem is you could have a working file name that the program always writes to. When it has finished it renames the file (or when it is starting, if it sees that filename it can rename it).
__________________
There are no computers in heaven!
Reply With Quote
  #7  
Old 01-22-2013, 06:24 AM
surfR2911 surfR2911 is offline
Contributor
 
Join Date: Oct 2009
Posts: 719
Default Student deception and saving counter value(s) in app settings

Quote:
Originally Posted by jamietax
1. The files have to be saved anonymously because this is an experiment where I manipulate feedback and see how it influences students.

2. Due to the reasons above the students are also not supposed to know where or how their data is being saved.
Are the students going to have unsupervised access to the computers?

If they do I'm sure eventually one of them may find the files (if they make an effort to look),
and since they are just text files they will be quite easily open and read using Notepad.

If preventing the students from reading the files is a goal you might think about writing them as binary (instead of text) files.
This will make them a little more difficult to read.
Binary with a little encryption would make it even harder.
Quote:
Originally Posted by jamietax
I am not able to do this because the variable 'Filename' is not declared on this form,
but I can't declare it without reinitializing the file counter and I don't want 20 text files per participant, just one.
If you are going with the counter approach then it would probably be wise to save
the counter value(s) separately each time the program shuts down.
Then the saved values can be read back into your program when it's run again.

.Net has an in-built way to do that.
Here is a little tutorial.
There's also some related code on this old MSDN page.
Reply With Quote
  #8  
Old 01-22-2013, 06:27 AM
PlausiblyDamp's Avatar
PlausiblyDampSaving a NEW text file each time the program runs PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

If you need an anonymous way of tracking things then something like a Guid might be be worth considering.

If the school has a database or not it doesn't prevent you using something like an access mdb or a sql express database. These wouldn't require the school to already have a database in place.

If you are wanting to do further analysis of the data then storing it in text files is going to make this difficult, databases are designed for this kind of searching and reporting tasks.
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #9  
Old 01-22-2013, 06:32 AM
surfR2911 surfR2911 is offline
Contributor
 
Join Date: Oct 2009
Posts: 719
Default Databases - a definite alternative..as is encryption..

Quote:
Originally Posted by PlausiblyDamp
If you are wanting to do further analysis of the data then storing it in text files is going to make this difficult, databases are designed for this kind of searching and reporting tasks.
I agree (and that's what I meant back in my post #3 when I said I agreed to what Gruff was saying in point #3 of post #2).
However I don't think that jamietax seems to eager to go in that direction:
Quote:
Originally Posted by jamietax (post #4)
3. The program is going to be used at multiple schools so I don't think a database would work, but I am not really sure.
Is there going to have to be any kind of write-up on this experiment after its done.
If so a queried database can be used to help make up some nice charts and reports.

Re: Encryption
There's a lots of VB.Net RSA Encryption articles around and I found a demo here.
Of course, make sure to right click on TestApp in the Solution Explorer and choose "Set As Startup project" otherwise you get that stupid class library startup error.

Last edited by surfR2911; 01-22-2013 at 06:47 AM.
Reply With Quote
  #10  
Old 01-22-2013, 10:11 AM
Gruff's Avatar
GruffSaving a NEW text file each time the program runs Gruff is offline
Bald Mountain Survivor

Retired Moderator
* Expert *
 
Join Date: Aug 2003
Location: Oregon, USA - deceased
Posts: 6,440
Default

I see an issue that each school will be generating files of the same name.
Participant0, Participant1, Participant2, Etc...
I would suggest Working a school ID into the name of each file, so that they do not get jumbled up when you try to pull some information out of the files at the end.
Perhaps "Participant_001_1
---
Now back to talking about a database. Most database's come with built in security. among other options they can be locked with a password. Text files are wide open.

Your VB program can read and write to a database without the students knowing what is going on behind the scenes.
---
__________________
Burn the land and boil the sea
You can't take the sky from me


~T
Reply With Quote
  #11  
Old 01-22-2013, 10:52 AM
AtmaWeapon's Avatar
AtmaWeaponSaving a NEW text file each time the program runs AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

There's two problems here: the question you asked and concerns about using text files for storage.

The Question You Asked
You want to save a file and guarantee that it's unique each time. The simplest possible thing is to look at the filesystem, see what number you used last, and use the next one. Suppose the format is "filenameX.txt", where X is the number:
Code:
Private Function GetNextFilename() As String
    Dim nextNumber = GetNextNumber()
    Dim fileName = String.Format("filename{0}.txt", nextNumber)
    Return fileName
End Function

Private Function GetNextNumber() As Integer
    Dim pathToFiles = "C:\temp\data"
    Dim files() = System.IO.Directory.GetFiles(pathToFiles, "*.txt")
    Dim max = 0
    For Each filename In files
        Dim current = GetNumberFromFilename(filename)
        If current > max Then
            max = current
        End If
    Next

    Return max + 1
End Function

Private Function GetNumberFromFilename(filename As String) As Integer
    Dim namePart = "filename"
    Dim digitIndex = namePart.Length
    Dim name = System.IO.Path.GetFileNameWithoutExtension(filename)
    Dim digits = name.Substring(digitIndex)

    Return Integer.Parse(digits)
End Function
Enumerating the files can be slow if there's lots of them. That's why you might do it once and save the number somewhere so you don't have to check again.

There's other ways to improve it though. Suppose you give each participant a unique ID number and save that. Then you don't have to check. You can also use the current date and time including the second; it's unlikely two people will be using the same machine at the same time (unless this is a web application; that's a different story and the code I posted above is also dangerous in this case.)

Concerns with using text files
You don't need to read this part if:
  • This project is code that is to be turned in for a grade in a class.
  • This project is being used to gather research for a project you'll turn in for a grade.
  • You're the only person who will ever administer this program and you are going to throw it away as soon as the project is over.
In those cases, you're not going to have to do long-term maintenance so there's no reason to not do the simplest thing. But if this is a legit project you are being paid to write and is going to run long-term (and potentially after you leave) then you should be concerned with doing the most correct thing.

Most people are getting stuck on the definition of "anonymous". If you only want, "I need to make sure I cannot tell which individual is associated with which file for the purposes of avoiding bias in interpretation of data" then text files with a simple identifier are probably good enough. If you are seeking, "The data is sensitive and there are privacy concerns if the data can be accessed" then your current plan is inadequate unless you are encrypting the data, but there are still concerns that someone who knows the order of participants can deduce who provided the responses.

There's another problem with text files: you have to write a program to load all of the data before you can interpret it. Databases come with query languages. Suppose you want to know how many people answered "C" to question 3. If you have a database you could write something like:
Code:
SELECT COUNT(*) FROM responses WHERE question_number = 3 AND response = 'C'
Without a database, here's pseudocode:
Code:
filenames := Get all files in the directory
for each file in filenames:
    open the file to read
    skip to the response for question 3
    if the response is 3:
        increment tally
A database doesn't require a big server or an expensive license. You can run MySQL or Postgres on a machine, and SQLite is a file-based database that requires no server. It's a little more complex to use one, but the complexity can be hidden behind abstraction layers if done right.

Either way, your "multiple schools" requirement is going to make any simple "increment the number" scheme for making filenames unique difficult. I strongly suggest using some other strategy, taking the degree of anonymity it provides into account. I don't know enough about what you are doing to give good advice, and even if I did I don't know if I'm qualified to say anything other than "this is how I'd do it".
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #12  
Old 01-22-2013, 02:05 PM
jamietax jamietax is offline
Newcomer
 
Join Date: Jan 2013
Posts: 5
Default

Thank you everyone for the suggestions. Unfortunately my problem is still not fixed. I am not using a database for the following reasons

1) This program is only being used for research purposes. Nobody other than me is going to use it.
2) I do not have a server or any money for a license
3) The computers will not have internet access while the program is running
4) Even if the data was in a database I would still have to analyze it with another software because I need to use advanced statistical analyses (SEM, MANCOVAs, and so on)
5) I don't know how the databases work and don't have time between now and Monday (when the data collection starts) to figure it out

In response to other issues that people have mentioned in regard to text files
1) The students will not have access to the computers once finished with the program
2) The data from all of the text files is read into SPSS (a statistical analysis software) with a python script so that I can analyze my results, so once I am finished with the data collection process I will not work with the text files anymore
3) Not only will each school generate the same text file names, but so will each computer. This is okay with me. Only 240 participants are going to use the program I am just going to change the text file name before I put them all onto one computer.

The reason that I want a new file name each time the program is ran is because 20 students will go through the program and then about 10 minutes after they are finished a new group of students will come in and go through the program on the same computers. For logistical reasons it would be easier if I didn't have to remove the text file before the next group of students come in.

I have tried using...
...a counter - this only works if I declare it as a global variable which then causes other problems
...saving the file as the date and time - this creates multiple text files for the same participant
...renaming the file at the end - Here I got an error message that the name can not be relative or absolute and since the name always has to be something different this option doesn't work

Any other suggestions are very much appreciated I have been working on this problem for about 20 hours and I am an educational researcher not a programmer.
Reply With Quote
  #13  
Old 01-22-2013, 04:47 PM
AtmaWeapon's Avatar
AtmaWeaponSaving a NEW text file each time the program runs AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Quote:
Originally Posted by jamietax View Post
I have tried using...
...a counter - this only works if I declare it as a global variable which then causes other problems
...saving the file as the date and time - this creates multiple text files for the same participant
...renaming the file at the end - Here I got an error message that the name can not be relative or absolute and since the name always has to be something different this option doesn't work
All three of these work when implemented properly. If you have tried them and they failed, you should post code so we can tell you where you went wrong.

Specifically:
  • The only problem the global variable should have is it won't be persisted if you shut the program down (unless you write code to do so.) There should be one place that reads it and one place that changes it. There's no reason for anything but the part of the program that writes the file to know about this variable.
  • I'm perplexed how a time-based approach creates multiple files. I'm under the impression that one person sits down, opens the program, uses it, then closes it. So your program should start, note the time, create the file, then use that filename for the entirety of the program. Don't generate a filename every time you want to write to it if your filename will change every time you ask.
  • If your code was based on mine, I'm curious to see more details. I didn't test against actual files so much as making sure I parsed filenames right. Understanding the difference between absolute and relative paths is a fundamental part of using the filesystem, and I'd be glad to help you figure this out.

There aren't really many ways to make file names unique that have not been discussed or aren't so exotic as to be impractical. I've used all of the methods discussed. If there is an error, it is within your code and since we cannot see it we cannot help you. The symptoms of some of the problems sound like design issues.

This part will sound harsh but is an honest technical assessment; don't read it if you have soft skin.
I understand you are not a programmer by trade but to some extent writing software is never easy. Compared to mathematics, your program is on the level of Algebra II. That is to say a veteran it is trivial but if it's one of your first projects, trying to learn all you need in two weeks is not just a monumental task, it's impossible. One can certainly read a book and have a passing familiarity with a lot of the concepts, but actually building a tool of complexity that does what you want requires knowing more than the name of the command that writes to a file.

So I sympathize with you, but I need to see your code to tell you what is broken. I have a strong feeling you don't understand how references work, and that's what would make a class-level counter really difficult to get right. But I don't want to spend a lot of time writing explanations of concepts irrelevant to the problem at hand. I promise you all three of these techniques work. You're not a veteran programmer so the concepts are frustratingly difficult. There's nothing wrong with being wrong in programming. You learn more from making mistakes than you do from getting it right. But we can't help if we can't see how you got it wrong.

TL;DR:
If I don't see code, you didn't try.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #14  
Old 01-23-2013, 03:18 AM
jamietax jamietax is offline
Newcomer
 
Join Date: Jan 2013
Posts: 5
Default

Thanks for taking the time to try to explain things to me. You are right, my main problem is that I don't have a deep enough understanding of programming (even the easy languages like Visual Basic). This is my first project and might also be the last time that I program something. Below is the way that I finally got it to work.

Dim Filename As String
Dim Counter As Integer
Dim fileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
fileList = My.Computer.FileSystem.GetFiles("C:\VB Material\data\")
Counter = fileList.Count

Filename = "participant" & CStr(Counter) & ".txt"

My.Computer.FileSystem.RenameFile("C:\VB Material\data\participant.txt", Filename)

I am not sure what exactly was wrong with the code the first time, but after many hours and a high level of frustration I finally got it to work

Thanks for taking the time to answer my questions!
Reply With Quote
  #15  
Old 01-23-2013, 08:59 AM
AtmaWeapon's Avatar
AtmaWeaponSaving a NEW text file each time the program runs AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

That's... a more simple implementation of what I did. The only downside is if you delete a file in the middle it's going to try and create a duplicate, but odds are you don't plan on deleting any files so that's a non-issue. Good work!
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply

Tags
saving text files


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
 
Saving a NEW text file each time the program runs
Saving a NEW text file each time the program runs
 
-->