使用 in VB.net 的条件定义
Conditional Definition with Using in VB.net
我想避免重复代码以有条件地写入日志文件,正如我在下面所做的那样。 VB.net有没有更好的解决办法?
If Not System.IO.File.Exists(log_file_address) Then
Using log_file_stream as New System.IO.StreamWriter(log_file_address)
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
Else
Using log_file_stream As IO.StreamWriter = System.IO.File.AppendText(log_file_address)
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
End If
可能是这样的:
Using log_file_stream as If(System.IO.File.Exists(log_file_address), _
System.IO.File.AppendText(log_file_address), _
New System.IO.StreamWriter(log_file_address))
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
StreamWriter
的构造函数有一个 overload,其参数采用文件路径字符串和布尔开关来指示是否应该过度追加。请注意,如果文件不存在,则此参数无效,构造函数会创建一个新文件。
因此更改并让构造函数负责检查文件是否存在。
Using log_file_stream as New System.IO.StreamWriter(log_file_address, True)
'Write to log file...
End Using
我想避免重复代码以有条件地写入日志文件,正如我在下面所做的那样。 VB.net有没有更好的解决办法?
If Not System.IO.File.Exists(log_file_address) Then
Using log_file_stream as New System.IO.StreamWriter(log_file_address)
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
Else
Using log_file_stream As IO.StreamWriter = System.IO.File.AppendText(log_file_address)
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
End If
可能是这样的:
Using log_file_stream as If(System.IO.File.Exists(log_file_address), _
System.IO.File.AppendText(log_file_address), _
New System.IO.StreamWriter(log_file_address))
log_file_stream.Writeline (current_time_string)
log_file_stream.Writeline (" ")
log_file_stream.Writeline (log_message)
log_file_stream.Close()
End Using
StreamWriter
的构造函数有一个 overload,其参数采用文件路径字符串和布尔开关来指示是否应该过度追加。请注意,如果文件不存在,则此参数无效,构造函数会创建一个新文件。
因此更改并让构造函数负责检查文件是否存在。
Using log_file_stream as New System.IO.StreamWriter(log_file_address, True)
'Write to log file...
End Using