Click here to Skip to main content
15,887,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using Visual Basic .NET to create a command prompt-like application for a project, and I need it to start writing all user input to a file when the user types in a command to do so.



What I have tried:

VB
 Console.Write(DateTime.Now.ToString("hh:mm tt") & " SRCLOS> ")

        Console.ForegroundColor = ConsoleColor.White
        Dim x = Console.ReadLine().ToLower
        If echoen = True Then
            Dim serer As StreamWriter = New StreamWriter(Convert.ToString(My.Settings.path))

            serer.WriteLine(DateTime.Now.ToString("hh:mm ") & " | " & " " & x)

        End If
        If x.Contains("$ping ") Then
            Try
                host = x.Substring(6)
                Console.WriteLine("Pinging " & host)
                Try


                    ' Create a buffer of 32 bytes of data to be transmitted. 
                    Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                    Dim buffer As Byte() = Encoding.ASCII.GetBytes(data)
                    Dim timeout As Integer = 250
                    Dim reply As PingReply = pingSender.Send(host, timeout, buffer, options)
                    If reply.Status = IPStatus.Success Then
                        Console.ForegroundColor = ConsoleColor.Yellow
                        Console.WriteLine("Address: {0}", reply.Address.ToString())
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime)
                        Console.WriteLine("Time to live: {0}", reply.Options.Ttl)
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length)
                    Else
                        err("Ping failed. Please check the host and your network.")
                    End If
                Catch ex As Exception
                    err("The given server '" & host & "' couldn't be found. Check the address and your network connection. 0x0P1")
                End Try
ElseIf x.Contains("!switch ") Then
            Dim xro = x.Substring(8)
            If xro = "echo" Then
                If echoen = False Then
                    echoen = True
                    paeth = "srclosecho " & DateTime.Now.ToString("dd-mm-yyyy hh-mm") & ".txt"

                    ' Create or overwrite the file.


                    ' Add text to the file.     
                    My.Settings.path = DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") & ".txt"
                    My.Settings.currentpath = My.Settings.path
                    fs = New StreamWriter(Convert.ToString(My.Settings.path))
                    fs.WriteLine(DateTime.Now.ToString("hh:mm ") & "ECHO was turned ON.")
                    fs.Close()
                    Console.WriteLine("ECHO is on.")
                Else
                    echoen = False
                    fs.WriteLine(DateTime.Now.ToString("hh:mm ") & "ECHO was turned OFF.")
                    fs.Close()
                    Console.WriteLine("ECHO is off.")
                End If
            End If
        Else err("The Command '" & x & "' was not found in the directory. 0x001")
        End If


If I run this code, the first input is stored, but the next input gives the following exception:

System.IO.IOException was unhandled
  HResult=-2147024864
  Message=The process cannot access the file 'C:\Users\Sekhara Pramod\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\04-05-2018 11-11-40.txt' because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
       at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
       at System.IO.StreamWriter..ctor(String path)
       at ConsoleApplication1.Module1.Main()
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 
Posted
Updated 4-May-18 19:47pm

1 solution

Look at the error message, it's pretty explicit:
Quote:
The process cannot access the file 'C:\Users\Sekhara Pramod\...\Debug\04-05-2018 11-11-40.txt' because it is being used by another process.
You create a StreamWriter and you write to it:
VB
Dim serer As StreamWriter = New StreamWriter(Convert.ToString(My.Settings.path))

 serer.WriteLine(DateTime.Now.ToString("hh:mm ") & " | " & " " & x)
but that is all you do. When the block it is in goes out of scope - almost immediately, the if block that contains it ends with the next line - it leaves the StreamWriter open which "blocks" the file for next time. And since this program doesn't use enough memory to start the Garbage Collector, the StreamWriter will remain in existence and open until your app closes.
Either Close and Dispose the Stream when you are finished with it (a Using Statement[^] is a good way) or just use File.AppendAllText instead:
VB
If echoen = True Then
    File.AppendAllText(Convert.ToString(My.Settings.path), DateTime.Now.ToString("hh:mm ") & " | " & " " & x & Environment.NewLine)
End If
 
Share this answer
 
Comments
Member 13812397 5-May-18 6:33am    
I replaced the echoen=false statement as well and now it runs smooth. Thank You!
OriginalGriff 5-May-18 7:35am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900