In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you the "C # file operation, reading files, Debug/ trace class example analysis", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "C# file operation, reading files, Debug/ trace class example analysis" this article.
1. File operation
This code is under System.Private.CoreLib, and the code in System.IO.File is simplified and used by CLR.
When using a file, it is necessary to judge in advance whether the file path exists. There should be many places to use the file in the daily project. You can unify a method to determine whether the file exists:
Public static bool Exists (string? Path) {try {/ / can string? Change it to string if (path = = null) return false; if (path.Length = = 0) return false; path = Path.GetFullPath (path); / / After normalizing, check whether path ends in directory separator. / / Otherwise, FillAttributeInfo removes it and we may return a false positive. / / GetFullPath should never return null Debug.Assert (path! = null, "File.Exists: GetFullPath returned null"); if (path.Length > 0 & & PathInternal.IsDirectorySeparator (path [^ 1])) {return false;} return InternalExists (path) } catch (ArgumentException) {} catch (NotSupportedException) {} / / Security can throw this on ":" catch (SecurityException) {} catch (IOException) {} catch (UnauthorizedAccessException) {} return false;}
It is recommended that when the path is finally processed in the project, it is converted to an absolute path:
Path.GetFullPath (path)
Of course, the relative path will be correctly identified by .NET, but for operation and maintenance problems and various considerations, the absolute path is easy to locate the specific location and troubleshooting.
When writing code, use relative paths, don't write dead, and improve flexibility; turn it into absolute paths at run time
The above NotSupportedException and other exceptions are all kinds of exceptions that may occur in operation files. For cross-platform applications, these exceptions may be very common. Identifying and handling the exception types in advance can optimize the file processing logic and facilitate the screening of processing errors.
2. Read the file
This code is in System.Private.CoreLib.
There is a way to read a file and convert it to byte [] as follows:
Public static byte [] ReadAllBytes (string path) {/ / bufferSize = = 1 used to avoid unnecessary buffer in FileStream using (FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)) {long fileLength = fs.Length; if (fileLength > int.MaxValue) throw new IOException (SR.IO_FileTooLong2GB) Int index = 0; int count = (int) fileLength; byte [] bytes = new byte [count]; while (count > 0) {int n = fs.Read (bytes, index, count); if (n = 0) throw Error.GetEndOfFile () Index + = n; count-= n;} return bytes;}}
You can see the use of FileStream. If you simply read the contents of the file, you can refer to the code in it:
FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1)
The above code also corresponds to File.ReadAllBytes. Inside File.ReadAllBytes, InternalReadAllBytes is used to handle document reading:
Private static byte [] InternalReadAllBytes (String path, bool checkHost) {byte [] bytes / / the constructor of this FileStream is not public, and developers cannot use using (FileStream fs = new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName (path), false, false, checkHost)) {/ / Do a blocking read int index = 0; long fileLength = fs.Length If (fileLength > Int32.MaxValue) throw new IOException (Environment.GetResourceString ("IO.IO_FileTooLong2GB")); int count = (int) fileLength; bytes = new byte [count]; while (count > 0) {int n = fs.Read (bytes, index, count) If (n = 0) _ Error.EndOfFile (); index + = n; count-= n;}} return bytes;}
This section shows that we can safely use the functions in the File static class, because some logic has been handled in it and the file is automatically released.
If we manually new FileStream, then we have to judge some situations, in order to avoid using the Times wrong, it is best to refer to the above code.
The .NET file stream cache size defaults to 4096 bytes:
Internal const int DefaultBufferSize = 4096
This code is defined in the File class, the developer cannot set the cache block size, in most cases, 4k is the optimal block size.
The upper limit of file size for ReadAllBytes is 2 GB.
3. Debug, Trace
The namespaces of these two classes provide System.Diagnostics,Debug and Trace with a set of methods and properties that help debug your code.
None of the functions in Debug are valid in Release, and all output streams are not displayed on the console, and listeners must be registered to read them.
Debug can print debug information and check logic using assertions to make the code more reliable without affecting the performance and code size of the shipped product.
Such output methods include Write, WriteLine, WriteIf, and WriteLineIf, where the output is not printed directly to the console.
To print debug information to the console, you can register the listener:
ConsoleTraceListener console = new ConsoleTraceListener (); Trace.Listeners.Add (console)
Note that Debug above .NET Core 2.x does not have Listeners because Debug uses Trace listeners.
We can register listeners with Trace.Listeners so that listeners are set equivalently relative to Debug.
Trace.Listeners.Add (new TextWriterTraceListener (Console.Out)); Debug.WriteLine ("aa")
Listeners in .NET Core all inherit TraceListener, such as TextWriterTraceListener, ConsoleTraceListener, DefaultTraceListener.
If you need to export to a file, you can inherit TextWriterTraceListener, write file stream output, or use DelimitedListTraceListener.
Example:
TraceListener listener = new DelimitedListTraceListener (@ "C:\ debugfile.txt"); / / Add listener. Debug.Listeners.Add (listener); / / Write and flush. Debug.WriteLine ("Welcome")
To handle the above method output console, you can also use the
ConsoleTraceListener console=.Listeners.Add (console); / / equivalent to var console= new TextWriterTraceListener (Console.Out)
To format the output stream, you can use the following attributes to control typesetting:
Property indicates that AutoFlush gets or sets a value indicating whether Listeners should be called on Flush () after each write. IndentLevel gets or sets the indentation level. IndentSize gets or sets the number of spaces to indent. / 1. Debug.WriteLine ("One"); / / Indent and then unindent after writing. Debug.Indent (); Debug.WriteLine ("Two"); Debug.WriteLine ("Three"); Debug.Unindent (); / / End. Debug.WriteLine ("Four"); / / Sleep. System.Threading.Thread.Sleep (10000); One Two ThreeFour
The .assert () method is very helpful for us to debug the program, and Assert sends a strong message to the developer. In IDE, assertions interrupt the normal operation of the program, but do not terminate the application.
The most intuitive effect of .Assert () is the assertion location of the output program.
Trace.Listeners.Add (new TextWriterTraceListener (Console.Out)); int value =-1; / / A. / / If value is ever-1, then a dialog will be shown. Debug.Assert (value! =-1, "Value must never be-1."); / / B. / / If you want to only write a line, use WriteLineIf. Debug.WriteLineIf (value =-1, "Value is-1.");-DEBUG ASSERTION FAILED-Assert Short Message-Value must never be-1.Murray-Assert Long Message-at Program.Main (String [] args) in. Program.cs:line 12Value is-1.
Debug.Prinf () can also output information, which behaves in accordance with the printf function of the C language, writing a message followed by a line Terminator, which by default is a carriage return followed by a newline character.
When running a program in IDE, using methods such as Debug.Assert (), Trace.Assert (), and so on, IDE asserts when the condition is false, which is equivalent to a conditional breakpoint.
In a non-IDE environment, the program will output some information, but there will be no interruption effect.
Trace.Listeners.Add (new TextWriterTraceListener (Console.Out)); Trace.Assert (false); Process terminated. Assertion Failed at Program.Main (String [] args) in C:\ ConsoleApp4\ Program.cs:line 44
Personally, I think Debug and Trace can be introduced into the project and used in conjunction with the logging component. Debug and Trace are used to record the diagnostic information of the program to facilitate the troubleshooting of program problems in the future; logs are used to record business processes, data information and so on.
The principle of .assert () is to do nothing on true, to call the Fail function on false, and to do nothing by default if you don't register the listener.
The only thing .assert () can do is to execute the Fail method when the condition is false. Of course, we can also call the Fail method manually. The code for Fail is as follows:
Public static void Fail (string message) {if (UseGlobalLock) {lock (critSec) {foreach (TraceListener listener in Listeners) {listener.Fail (message); if (AutoFlush) listener.Flush () } else {foreach (TraceListener listener in Listeners) {if (! listener.IsThreadSafe) {lock (listener) {listener.Fail (message) If (AutoFlush) listener.Flush ();} else {listener.Fail (message); if (AutoFlush) listener.Flush () The above is all the contents of the article "File manipulation, File Reading, and sample Analysis of Debug/ track classes in C#". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.