Results 1 to 15 of 15

Thread: [RESOLVED] Issues when writing to a File using StreamWriter

  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Resolved [RESOLVED] Issues when writing to a File using StreamWriter

    I have tried to find someone with the same issue but none are what I am looking for.

    I am using a stream writer to type a string into a file (not a text file, just a "File" with no .txt or any extension) and the data writes to the file, but as soon as i open the file and view the data it erases it upon closing the file. I use the same method to write to an actual .txt file and there is no issue, so i am wondering if it is because it is a "nonlabeled" file. Though it has to be that way so another program in LabView can open the data.

    It is pretty frustrating and i can not figure out what is causing it to do that. I posted my code below (idk if it is formatted correctly this is my first post)

    Code:
        Private Sub Testing_Values_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles Testing_Values.DataChanged
            Dim mydriver As New EthernetIPforCLXCom
            mydriver.IPAddress = "111.111.1.111"  'NOT SUBJECT TO CHANGE nor my real IP address
    
            Dim UNLOADCARRIER_V As String = mydriver.Read(UNLOADCARRIER)
            UNLOADCARRIER_N = Convert.ToInt32(UNLOADCARRIER_V)
            Dim UNLOADCOLOR As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Paint_Color"}"))
            Dim UNLOADNUMBER As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Part_Number"}"))
            Dim UNLOADNAME As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Name"}"))
            'END
            If UNLOADCOLOR <> "0" Then
                If UNLOADNUMBER <> String.Empty Or UNLOADNUMBER <> "" Then
                    If UNLAST_CAR <> UNLOADCARRIER_N Then
                        testdata = ($"{DateTime.Now.ToString("h:mm:ss.fff tt M/dd/yyyy")},{"P"}")
                        valuedata_unload = ($"{UNLOADNUMBER},{Date.Now.ToShortDateString},{shift}")
                        Using sw4 As New StreamWriter(testfile1, fileExists4)
                            sw4.WriteLine($"{testdata}")
                            sw4.Close()
                        End Using
                        UNLAST_CAR = UNLOADCARRIER_N
                    End If
                End If
            End If
        End Sub

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,803

    Re: Issues when writing to a File using StreamWriter

    Why don't simply use IO.File.AppendAllText (documentation) and omit the extension? E.g.
    Code:
    Try
        Dim fileLocation = "some-file-no-ext"
        Dim data = "Change me to something meaningful."
        IO.File.AppendAllText(fileLocation, data & Environment.NewLine)
    Catch ex As Exception
        ' do something with the exception
        Console.WriteLine(ex.Message)
    End Try
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    I tried using the IO.File.AppendAllText but the same issue still occurred. I rewrote labview code to read a .txt file and the issue seems to be resolved. I am not sure if it was just a file incompatibility for the stream writer or if my labview code was somehow erasing the data.

  4. #4
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,803

    Re: Issues when writing to a File using StreamWriter

    My guess is the latter.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  5. #5
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,776

    Re: Issues when writing to a File using StreamWriter

    I tried to emulate what you say is happening. I think this captures what you said.

    Code:
            Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            path = IO.Path.Combine(path, "FOOfile")
            Dim alpha As String = "abcdefghijklmnopqrstuvwxyz"
            Using sw As New IO.StreamWriter(path, True)
                For Each c As Char In alpha
                    sw.Write(c)
                Next
            End Using
    When I opened 'FOOfile' (no extension) it contained,

    Code:
    abcdefghijklmnopqrstuvwxyz
    After running again it the file contained,
    Code:
    abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,155

    Re: Issues when writing to a File using StreamWriter

    If you can open that file in some other program, and the data is there, but when you open it with LabView, it is first there, then goes away upon closing, then it's the labview that is doing it. I don't know what labview is, or how it works, but there are several ways this could be happening. For one thing, the other part of the file (if there is another part) might contain some kind of file length information, so all that gets written is that length, thereby ignoring your extra stuff. More likely, though, it is reading everything in, then writing everything back out...but not quite everything, as it's forgetting about your extra stuff.

    Either way, I think you've determined that the issue isn't due to writing to the file. That part appears to be working correctly, it's something about what happens next that is screwing up the file.
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    Hello all,

    So I removed the labview section where it views the code and just let the vb code write to the file, and I am still having an issue with the text file retaining the data.

    VB will append the file like its suppose to but it will randomly erase the entirety of the file and begin writing again. I tested to make sure that the code which checks the file path to ensure the file exists works, since if the file isnt there it will create a new one. I set the fileexist variable to true so it will always assume the file is valid. Yet I am still having issues, I tried using the IO.File.AppendAllText instead of stream write and the situation still happens... I am at a loss as to what is causing this.

    I have multiple stream writers and this is the only one I am having problems with. Which is crazy because I copied and pasted the codes since I knew that it works, just not with this one. I think I have narrowed it down to being something within the VB code, I am just not sure what.

  8. #8

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    This was the way I used the AppendAllText

    Code:
        Private Sub Testing_Values_DataChanged(sender As Object, e As Drivers.Common.PlcComEventArgs) Handles Testing_Values.DataChanged
            Dim mydriver As New EthernetIPforCLXCom
            mydriver.IPAddress = "111.111.1.111"  'NOT SUBJECT TO CHANGE
            'Carrier value at load station
            fileExists4 = True
    
            Dim UNLOADCARRIER_V As String = mydriver.Read(UNLOADCARRIER)
            UNLOADCARRIER_N = Convert.ToInt32(UNLOADCARRIER_V)
            Dim UNLOADCOLOR As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Paint_Color"}"))
            Dim UNLOADNUMBER As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Part_Number"}"))
            Dim UNLOADNAME As String = mydriver.Read(($"{"Carrier_Info["}{UNLOADCARRIER_V}{"].Name"}"))
            'END
            If UNLOADCOLOR <> "0" Then
                If UNLOADNUMBER <> String.Empty Or UNLOADNUMBER <> "" Then
                    If UNLAST_CAR <> UNLOADCARRIER_N Then
                        testdata = ($"{DateTime.Now.ToString("h:mm:ss.fff tt M/dd/yyyy")},{"P"}")
                        valuedata_unload = ($"{UNLOADNUMBER},{Date.Now.ToShortDateString},{shift}")
                        Try
                            IO.File.AppendAllText(testfile1, testdata & Environment.NewLine)
                        Catch ex As Exception
                            Console.WriteLine($"{"Data failed to save:"}{ex}")
                        End Try
                        UNLAST_CAR = UNLOADCARRIER_N
                    End If
                End If
            End If
        End Sub
    End Class

  9. #9
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,205

    Re: Issues when writing to a File using StreamWriter

    We can only speculate, since you are only providing part of your code. You obviously have other relevant code you haven't posted, since, for example, you don't show any code where your variable of testfile1 is being populated.

    You say you have multiple stream writers, and I'm assuming you mean that you have them in use inside of this program. The most likely scenario is that some other code that you haven't posted is responsible for either deleting the file completely or creating a new empty file in its place. And one possible cause of that is because, as you said, you "copied and pasted" this code that worked, and maybe you should have changed some variable names in the "pasted" code, but you didn't, and so now you are accidentally reusing a global variable (like testfile1) somewhere else, when you should have created some new global variable (or used function parameters, etc).

    Good luck.

  10. #10

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    Quote Originally Posted by OptionBase1 View Post
    We can only speculate, since you are only providing part of your code. You obviously have other relevant code you haven't posted, since, for example, you don't show any code where your variable of testfile1 is being populated.

    You say you have multiple stream writers, and I'm assuming you mean that you have them in use inside of this program. The most likely scenario is that some other code that you haven't posted is responsible for either deleting the file completely or creating a new empty file in its place. And one possible cause of that is because, as you said, you "copied and pasted" this code that worked, and maybe you should have changed some variable names in the "pasted" code, but you didn't, and so now you are accidentally reusing a global variable (like testfile1) somewhere else, when you should have created some new global variable (or used function parameters, etc).

    Good luck.
    The code is quite long, I don't mind posting it in its entirety, I have double checked all the variables and they are all where they are suppose to be. I renamed them to make it easier to tell which file corresponds to each file.

  11. #11
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,205

    Re: Issues when writing to a File using StreamWriter

    We need to see all the code that does any sort of file interaction.

  12. #12

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    I have attached the full length of the code, it was written using Visual Studios 2022
    Attached Files Attached Files
    Last edited by paintman; Apr 15th, 2024 at 02:16 PM.

  13. #13
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,205

    Re: Issues when writing to a File using StreamWriter

    I posit that your code is causing the problem.

    You have this as a Form level variable:

    Code:
    Public testfile1 As String 'this is a variable since the file will change each year
    Then you have this a few lines later:

    Code:
    Public testfileExists As Boolean = File.Exists(testfile1)
    I would imagine that testfileExists will always evaluate to False when the program is first loaded, because testfile1 hasn't been assigned a value yet when that second line is executed.

    So, you need to shuffle stuff around. It might just be as easy as changing that second line to:

    Code:
    Public testfileExists As Boolean
    And then in MainForm_Load, do this:

    Code:
            testfile1 = ($"{testfile_folder}\{Date.Now.ToString("yyyy")}_P001.txt")
            testfileExists = File.Exists(testfile1)  ' Add this line

  14. #14

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    Quote Originally Posted by OptionBase1 View Post
    I posit that your code is causing the problem.

    You have this as a Form level variable:

    Code:
    Public testfile1 As String 'this is a variable since the file will change each year
    Then you have this a few lines later:

    Code:
    Public testfileExists As Boolean = File.Exists(testfile1)
    I would imagine that testfileExists will always evaluate to False when the program is first loaded, because testfile1 hasn't been assigned a value yet when that second line is executed.

    So, you need to shuffle stuff around. It might just be as easy as changing that second line to:

    Code:
    Public testfileExists As Boolean
    And then in MainForm_Load, do this:

    Code:
            testfile1 = ($"{testfile_folder}\{Date.Now.ToString("yyyy")}_P001.txt")
            testfileExists = File.Exists(testfile1)  ' Add this line
    Its strange though since this issue only happens with the valuefile_load and the testfile1 but I will certainly give this a try! Thank you for the advice

  15. #15

    Thread Starter
    New Member
    Join Date
    Apr 2024
    Posts
    11

    Re: Issues when writing to a File using StreamWriter

    This was my issue!! Thank you so much, this was driving me crazy. I appreciate everyone's help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width