Как сохранить все пользовательские данные в текстовом файле в консольном приложении?
Я использую Visual Basic .NET для создания приложения, похожего на командную строку, для проекта, и мне нужно, чтобы он начал записывать все вводимые пользователем данные в файл, когда пользователь вводит команду для этого.
Что я уже пробовал:
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
Если я запускаю этот код, то первый ввод сохраняется, но следующий ввод дает следующее исключение:
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: