如何将所有用户输入存储在控制台应用程序的文本文件中? [英] How do I store all user inputs in a text file in a console app?

查看:63
本文介绍了如何将所有用户输入存储在控制台应用程序的文本文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Visual Basic .NET为项目创建类似命令提示的应用程序,我需要它在用户键入命令时开始将所有用户输入写入文件。







我的尝试:



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

Console.ForegroundColor = ConsoleColor.White
Dim x = Console.ReadLine()。ToLower
如果 echoen = True 那么
< span class =code-keyword> Dim serer As StreamWriter = StreamWriter(转换.ToString(My.Settings.path))

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

结束 如果
如果 x.Contains( $ ping然后
尝试
host = x.Substring( 6
Console.WriteLine( Pinging& host)
尝试


' 创建一个32字节数据的缓冲区。
Dim data As String = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Dim buffer As Byte ()= Encoding.ASCII.GetBytes(data)
Dim timeout 作为 整数 = 250
Dim reply As PingReply = pingSender.Send(主机,超时,缓冲区,选项)
如果 reply.Status = IPStatus.Success 然后
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine( 地址:{0},reply.Address.ToString() )
Console.WriteLine( RoundTrip time:{0},reply.RoundtripTime)
Console.WriteLine( 生存时间:{0},reply.Options。 Ttl)
Console.WriteLine( 缓冲区大小:{0},reply.Buffer .Length)
Else
err( Ping失败。请检查主机和您的网络。
结束 如果
Catch ex As 异常
err( 给定服务器& host& 。检查地址和网络连接.0x0P1
结束 尝试
ElseIf x.Contains( !switch然后
Dim xro = x.Substring( 8
如果 xro = echo 然后
如果 echoen = False 那么
echoen = True
paeth = srclosecho& DateTime.Now.ToString( dd-mm-yyyy hh-mm)& .txt

' 创建或覆盖文件。


' 将文本添加到文件中。
My.Settings.path = DateTime.Now.ToString( dd-MM-yyyy hh-mm-ss)& 。txt
My.Settings.currentpath = My.Settings.path
fs = StreamWriter(Convert.ToString(My.Settings.path))
fs.WriteLine(DateTime.Now.ToString( hh:mm)& ECHO已打开。
fs.Close()
Console.WriteLine( < span class =code-string> ECHO已启用。)
否则
echoen = False
fs.WriteLine(DateTime.Now.ToString( hh: mm)& ECHO已转为OFF。
fs.Close()
Console.WriteLine( ECHO已关闭。
结束 如果
结束 如果
其他错误(< span class =code-string> 命令'& x&在目录中找不到 。0x001
结束 如果





如果我跑此代码存储第一个输入,但下一个输入提供以下异常:



 System.IO.IOException未处理
HResult = -2147024864
消息=进程无法访问文件'C:\ Users \Sekhara Pramod \Documents\Visual Studio 2015 \Projects\ConsoleApplication1 \ConsoleApplication1 \ bin \ Debug \ 04-05-2018 11-11-40.txt'因为它正被另一个进程使用。
Source = mscorlib
StackTrace:
at System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)
at System.IO.FileStream.Init(String path,FileMode mode ,FileAccess访问,Int32权限,布尔useRights,FileShare共享,Int32 bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,字符串msgPath,布尔bFromProxy,布尔useLongPath,布尔checkHost)
at System.IO.FileStream..ctor(String path ,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,String msgPath,Boolean bFromProxy,Boolean useLongPath,Boolean checkHost)
at System.IO.StreamWriter.CreateFile(String path,Boolean append,Boolean checkHost) System.IO.StreamWriter..ctor上的
(String path,Boolean append,Encoding encoding,Int32 bufferSize,Boolean checkHost)
at System.IO.StreamWriter..ctor(String path)
在SystemApp.AppDomain._nExec的ConsoleApplication1.Module1.Main()
uteAssembly(RuntimeAssembly程序集,String [] args)
在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。运行(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:

解决方案

ping)然后
尝试
host = x.Substring( 6
Console.WriteLine( Pinging&主持人)
尝试


' 创建一个32字节数据的缓冲区。
Dim data As String = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Dim buffer As Byte ()= Encoding.ASCII.GetBytes(data)
Dim timeout 作为 整数 = 250
Dim reply As PingReply = pingSender.Send(主机,超时,缓冲区,选项)
如果 reply.Status = IPStatus.Success 然后
Console.ForegroundColor = ConsoleColor.Yellow
Console.WriteLine( 地址:{0},reply.Address.ToString() )
Console.WriteLine( RoundTrip time:{0},reply.RoundtripTime)
Console.WriteLine( 生存时间:{0},reply.Options。 Ttl)
Console.WriteLine( 缓冲区大小:{0},reply.Buffer .Length)
Else
err( Ping失败。请检查主机和您的网络。
结束 如果
Catch ex As 异常
err( 给定服务器& host& 。检查地址和网络连接.0x0P1
结束 尝试
ElseIf x.Contains( !switch然后
Dim xro = x.Substring( 8
如果 xro = echo 然后
如果 echoen = False 那么
echoen = True
paeth = srclosecho& DateTime.Now.ToString( dd-mm-yyyy hh-mm)& .txt

' 创建或覆盖文件。


' 将文本添加到文件中。
My.Settings.path = DateTime.Now.ToString( dd-MM-yyyy hh-mm-ss)& 。txt
My.Settings.currentpath = My.Settings.path
fs = StreamWriter(Convert.ToString(My.Settings.path))
fs.WriteLine(DateTime.Now.ToString( hh:mm)& ECHO已打开。
fs.Close()
Console.WriteLine( < span class =code-string> ECHO已启用。)
否则
echoen = False
fs.WriteLine(DateTime.Now.ToString( hh: mm)& ECHO已转为OFF。
fs.Close()
Console.WriteLine( ECHO已关闭。
结束 如果
结束 如果
其他错误(< span class =code-string> 命令'& x&在目录中找不到 。0x001
结束 如果





如果我跑此代码存储第一个输入,但下一个输入提供以下异常:



 System.IO.IOException未处理
HResult = -2147024864
消息=进程无法访问文件'C:\ Users \Sekhara Pramod \Documents\Visual Studio 2015 \Projects\ConsoleApplication1 \ConsoleApplication1 \ bin \ Debug \ 04-05-2018 11-11-40.txt'因为它正被另一个进程使用。
Source = mscorlib
StackTrace:
at System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)
at System.IO.FileStream.Init(String path,FileMode mode ,FileAccess访问,Int32权限,布尔useRights,FileShare共享,Int32 bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,字符串msgPath,布尔bFromProxy,布尔useLongPath,布尔checkHost)
at System.IO.FileStream..ctor(String path ,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,String msgPath,Boolean bFromProxy,Boolean useLongPath,Boolean checkHost)
at System.IO.StreamWriter.CreateFile(String path,Boolean append,Boolean checkHost) System.IO.StreamWriter..ctor上的
(String path,Boolean append,Encoding encoding,Int32 bufferSize,Boolean checkHost)
at System.IO.StreamWriter..ctor(String path)
在SystemApp.AppDomain._nExec的ConsoleApplication1.Module1.Main()
uteAssembly(RuntimeAssembly程序集,String [] args)
在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。运行(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:


查看错误消息,它非常明确:

引用:

该进程无法访问文件'C:\ Users \Sekhara Pramod \ ... \Debug \ 04-05-2018 11-11-40.txt',因为它正由另一个进程使用。

你创建一个StreamWriter并写入它:

  Dim  serer  As  StreamWriter =  StreamWriter(Convert.ToString(My.Settings.path))

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

但这就是你所做的一切。当它所在的块超出范围时 - 几乎立即,如果包含它的块以下一行结束 - 它使StreamWriter保持打开状态阻塞文件下一次。由于此程序没有足够的内存来启动垃圾收集器,StreamWriter将保持存在并打开,直到您的应用程序关闭。

完成后关闭并处理流( 使用声明 [ ^ ]是个不错的选择改为使用File.AppendAllText:

 如果 echoen =  True  然后 
File.AppendAllText(Convert.ToString(My.Settings.path),DateTime.Now.ToString( hh:mm)& < span class =code-string> |& & x& Environment.NewLine)
结束 如果


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:

 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: 

解决方案

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: 


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:

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:

If echoen = True Then
    File.AppendAllText(Convert.ToString(My.Settings.path), DateTime.Now.ToString("hh:mm ") & " | " & " " & x & Environment.NewLine)
End If


这篇关于如何将所有用户输入存储在控制台应用程序的文本文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆