Последнее обновление: 31.10.2015
Окна открытия и сохранения файла представлены классами OpenFileDialog и SaveFileDialog.
Они имеют во многом схожую функциональность, поэтому рассмотрим их вместе.
OpenFileDialog и SaveFileDialog имеют ряд общих свойств, среди которых можно выделить следующие:
-
DefaultExt
: устанавливает расширение файла, которое добавляется по умолчанию, если пользователь ввел имя файла без расширения -
AddExtension
: при значенииtrue
добавляет к имени файла расширение при его отсуствии. Расширение берется из
свойстваDefaultExt
илиFilter
-
CheckFileExists
: если имеет значениеtrue
, то проверяет существование файла с указанным именем -
CheckPathExists
: если имеет значениеtrue
, то проверяет существование пути к файлу с указанным именем -
FileName
: возвращает полное имя файла, выбранного в диалоговом окне -
Filter
: задает фильтр файлов, благодаря чему в диалоговом окне можно отфильтровать файлы по расширению. Фильтр задается в следующем формате
Название_файлов|*.расширение. Например,Текстовые файлы(*.txt)|*.txt
. Можно задать сразу несколько фильтров, для этого они разделяются
вертикальной линией |. Например,Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg
-
InitialDirectory
: устанавливает каталог, который отображается при первом вызове окна -
Title
: заголовок диалогового окна
Отдельно у класса SaveFileDialog можно еще выделить пару свойств:
-
CreatePrompt
: при значенииtrue
в случае, если указан не существующий файл, то будет отображаться сообщение о его создании -
OverwritePrompt
: при значенииtrue
в случае, если указан существующий файл, то будет отображаться сообщение о том, что файл будет перезаписан
Чтобы отобразить диалоговое окно, надо вызвать метод ShowDialog()
.
Рассмотрим оба диалоговых окна на примере. Добавим на форму текстовое поле textBox1 и две кнопки button1 и button2. Также перетащим с панели инструментов
компоненты OpenFileDialog и SaveFileDialog. После добавления они отобразятся внизу дизайнера формы. В итоге форма будет выглядеть примерно так:
Теперь изменим код формы:
public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; button2.Click += button2_Click; openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*"; saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*"; } // сохранение файла void button2_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.Cancel) return; // получаем выбранный файл string filename = saveFileDialog1.FileName; // сохраняем текст в файл System.IO.File.WriteAllText(filename, textBox1.Text); MessageBox.Show("Файл сохранен"); } // открытие файла void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.Cancel) return; // получаем выбранный файл string filename = openFileDialog1.FileName; // читаем файл в строку string fileText = System.IO.File.ReadAllText(filename); textBox1.Text = fileText; MessageBox.Show("Файл открыт"); } }
По нажатию на первую кнопку будет открываться окно открытия файла. После выбора файла он будет считываться, а его текст будет отображаться в
текстовом поле. Клик на вторую кнопку отобразит окно для сохранения файла, в котором надо установить его название. И после этого произойдет сохранение
текста из текстового поля в файл.
C# OpenFileDialog
C# OpenFileDialog control allows us to browse and select files on a computer in an application. A typical Open File Dialog looks like Figure 1 where you can see Windows Explorer like features to navigate through folders and select a file.
Figure 1
Creating a OpenFileDialog
We can create an OpenFileDialog control using a Forms designer at design-time or using the OpenFileDialog class in code at run-time (also known as dynamically). Unlike other Windows Forms controls, an OpenFileDialog does not have and not need visual properties like others. The only purpose of OpenFileDialog to display available colors, create custom colors and select a color from these colors. Once a color is selected, we need that color in our code so we can apply it on other controls.
Again, you can create an OpenFileDialog at design-time but it is easier to create an OpenFileDialog at run-time.
Design-time
To create an OpenFileDialog control at design-time, you simply drag and drop an OpenFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop an OpenFileDialog on a Form, the OpenFileDialog looks like Figure 2.
Figure 2
Adding an OpenFileDialog to a Form adds following two lines of code.
private System.Windows.Forms.OpenFileDialog openFileDialog1;
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
Run-time
Creating a OpenFileDialog control at run-time is merely a work of creating an instance of OpenFileDialog class, set its properties and add OpenFileDialog class to the Form controls.
First step to create a dynamic OpenFileDialog is to create an instance of OpenFileDialog class. The following code snippet creates an OpenFileDialog control object.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
ShowDialog method displays the OpenFileDialog.
openFileDialog1.ShowDialog();
Once the ShowDialog method is called, you can browse and select a file.
Setting OpenFileDialog Properties
After you place an OpenFileDialog control on a Form, the next step is to set properties.
The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 3.
Figure 3
Initial and Restore Directories
InitialDirectory property represents the directory to be displayed when the open file dialog appears first time.
openFileDialog1.InitialDirectory = @"C:\";
If RestoreDirectory property set to true that means the open file dialogg box restores the current directory before closing.
openFileDialog1.RestoreDirectory = true;
Title
Title property is used to set or get the title of the open file dialog.
openFileDialog1.Title = "Browse Text Files";
Default Extension
DefaultExtn property represents the default file name extension.
openFileDialog1.DefaultExt = "txt";
Filter and Filter Index
Filter property represents the filter on an open file dialog that is used to filter the type of files to be loaded during the browse option in an open file dialog. For example, if you need users to restrict to image files only, we can set Filter property to load image files only.
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
FilterIndex property represents the index of the filter currently selected in the file dialog box.
openFileDialog1.FilterIndex = 2;
Check File Exists and Check Path Exists
CheckFileExists property indicates whether the dialog box displays a warning if the user specifies a file name that does not exist. CheckPathExists property indicates whether the dialog box displays a warning if the user specifies a path that does not exist.
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
File Name and File Names
FileName property represents the file name selected in the open file dialog.
textBox1.Text = openFileDialog1.FileName;
If MultiSelect property is set to true that means the open file dialog box allows multiple file selection. The FileNames property represents all the files selected in the selection.
this.openFileDialog1.Multiselect = true;
foreach (String file in openFileDialog1.FileNames)
{
MessageBox.Show(file);
}
Read Only Checked and Show Read Only Files
ReadOnlyChecked property represents whether the read-only checkbox is selected and ShowReadOnly property represents whether the read-only checkbox is available or not.
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
Implementing OpenFileDialog in a C# and WinForms Applications
Now let’s create a WinForms application that will use an OpenFileDialog that has two Button controls, a TextBox, and a container control. The Form looks like Figure 4.
Figure 4
The Browse button click event handler will show an open file dialog and users will be able to select text files. The open file dialog looks like Figure 5.
Figure 5
The following code snippet is the code for Browse button click event handler. Once a text file is selected, the name of the text file is displayed in the TextBox.
private void BrowseButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = @"D:\",
Title = "Browse Text Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "txt",
Filter = "txt files (*.txt)|*.txt",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
The code for Browse Multiple Files button click event handler looks like following.
private void BrowseMultipleButton_Click(object sender, EventArgs e)
{
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "Select Photos";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
try
{
PictureBox imageControl = new PictureBox();
imageControl.Height = 400;
imageControl.Width = 400;
Image.GetThumbnailImageAbort myCallback =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap = new Bitmap(file);
Image myThumbnail = myBitmap.GetThumbnailImage(300, 300,
myCallback, IntPtr.Zero);
imageControl.Image = myThumbnail;
PhotoGallary.Controls.Add(imageControl);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
public bool ThumbnailCallback()
{
return false;
}
The output looks like Figure 6.
Summary
An OpenFileDialog control allows users to launch Windows Open File Dialog and let them select files. In this article, we discussed how to use a Windows Open File Dialog and set its properties in a Windows Forms application.
The Open File Dialog control (System.Windows.Forms.OpenFileDialog) allows you to open and read file contents such as texts from text files. The dialog allows you to browse your file system and pick a directory. You can type the name of the file that exist in the current directory or you can type the whole path of a file or directory in the File Name text box located at the bottom of the dialog.
The following table shows some useful properties of the OpenFileDialog control.
Property | Description |
---|---|
AddExtention | Specifies whether to automatically add an extension when the user omits the extension of the file he or she chooses. |
CheckFileExists | Specifies whether to initiate a warning if the user types a file that does not exist. |
CheckPathExists | Specifies whether to initiate a warning if the user types a path that does not exist. |
DefaultExt | The default extension to add when the user does not indicate a file extension. |
FileName | The file selected by the user. This can also be the default selected the file when the dialog shows up. |
FileNames | A collection of files that the user picked. |
Filter | Allows you to add a filter which are a special string indicating which types or files are only allowed to be opened by the user. |
FilterIndex | If multiple filters are present, this indicates which filter shows as the default starting with index 1. |
InitialDirectory | The initial directory that the OpenFileDialog will show. |
Multiselect | Tells whether the user can select multiple files. |
Title | The title of the dialog. |
The AddExtention property automatically adds an extension when the user does not indicate the file extension of the file name. The extension to add is specified by the DefaultExt property. The CheckFileExists and CheckPathExists methods are recommended to be set to true so the dialog will issue a warning message if it cannot find the specified file or directory. The InitialDirectory property specifies the initial directory that the dialog will show when you open it up. The Title property is the title of the dialog located at the title bar. The FileName property is the selected file selected or specified by the user. You can allow a user to select multiple files by setting the Multiselect property to true. You can then use the FileNames property to get the collection of selected file names.
Filtering Files
We can filter the files to be shown by their file types. We use the Filter property which accepts a string containing a special pattern. For example, we can set the dialog to only show text files by filtering the results to only files with .txt file extensions. The Filter property requires a special pattern.
Description1|FilterPattern1|Description2|FilterPattern2|...DescriptionN|FilterPatternN
We first start with a description telling about the type of file. We then follow it with a vertical bar (|) followed by the filter pattern. For example, the following pattern only shows the text files.
Text Files|*.txt
The description here is Text Files and the pattern is *.txt. The * character is a wildcard character which means any names. The .txtportion specifies the specific file extension. The filter pattern says any file with a file extension of .txt. You can also use the wildcard characters for many another purpose. For example, m*.txt is the pattern for all the text files that start with letter m. *r.txt is the pattern for all the text files that ends with letter r, *.* is the pattern for all kinds of files, *.t* is the pattern for all files that have a file extension that starts with letter t.
You can specify multiple filters. For example, the following pattern adds multiple filters.
Text Files|*.txt|Bitmap Files|*.bmp|All Files|*.*
You can select a filter using a combo box next to the file name text box of the dialog.
You can group a set of file extensions for a single description. For example, image files consist of different file extensions such as bmp, jpeg, or png. You simply separate the file extensions using semicolons.
Image Files|*.bmp;*.jpeg;*.png;*.gif
When you select this filter, then all of the files that matches one of the filter patterns will be shown.
OpenFileDialog Control Example
We will now create an example application that uses the basic capabilities of the OpenFileDialog control. The application will allow a user to browse for a text file and view its contents using a multiline text box. Please note that we need to import the System.IOnamespace in our code.
using System.IO;
Create a form similar to the one below. Use a multiline text box by setting the Multiline property to true. Set the Scrollbars property of the text box to both and the WordWrap property to false (optional). Drag an OpenFileDialog control from the toolbox to the form.
Double-click the button to create an event handler for its Click event. Again, import the System.IO namespace first at the top of the code. Use the following code for the event handler.
private void button1_Click(object sender, EventArgs e)
{
//Filter to only text files
openFileDialog1.Filter = "Text Files|*.txt";
//No initial file selected
openFileDialog1.FileName = String.Empty;
//Open file dialog and store the returned value
DialogResult result = openFileDialog1.ShowDialog();
//If Open Button was pressed
if (result == DialogResult.OK)
{
//Create a stream which points to the file
Stream fs = openFileDialog1.OpenFile();
//Create a reader using the stream
StreamReader reader = new StreamReader(fs);
//Read Contents
textBox1.Text = reader.ReadToEnd();
//Close the reader and the stream
reader.Close();
}
}
The first line adds a filter using the Filter property. We specified in the pattern to only allow the user to open text files. The second one assigns an empty string to the FileName so there is no file selected by default. We then open the OpenFileDialog using its ShowMethodproperty which returns a DialogResult value. The user can now choose a text file by browsing the system. When the user presses the Open button while a valid file is selected, then the method ShowDialog will return DialogResult.OK. We tested this using an ifstatement. We used the OpenFile method of the OpenFileDialog control and store it in a Stream object. The Stream object points to the selected file and we use this object to create a StreamReader object which is used to read the stream(the file). We used the ReadToEnd method of the StreamReader object to read all the contents of the file and return the result as trying. We then place the result inside the text box.
Execute the application and click the button. Browse for a text file and click Open. If the file the user types cannot be found, then an error will show up if the CheckFileExists and CheckPathExists properties are set to true. If the file is valid and you press Open, then the contents of the file will be shown in the text box.
This C# tutorial demonstrates the OpenFileDialog control in Windows Forms.
OpenFileDialog allows users to browse folders and select files.
It is available in Windows Forms and can be used with C# code. It displays the standard Windows dialog box. The results of the selection can be read in your C# code.
Intro. To begin developing your OpenFileDialog, you need to open your Windows Forms program in the Visual Studio designer and open the Toolbox pane. Find the OpenFileDialog entry and double-click on it.
Note: This entry describes a control that «displays a dialog box that prompts the user to open a file.»
With OpenFileDialog, you can only change properties in the Properties pane. Please select the openFileDialog1 icon in the tray at the bottom of the Visual Studio window, and then look at the Properties pane.
ShowDialog. You can open the OpenFileDialog that is in your Windows Forms program. The dialog will not open automatically and it must be invoked in your custom code. You will want to use an event handler to open the dialog in your C# code.
Here: We will use a button in this tutorial, which when clicked will open the dialog.
You can add a Button control—this can be clicked on to call into the OpenFileDialog window. To add a Button, find the Button icon in the Toolbox and drag it to an area in your Windows Forms window.
Tip: You can add an event to the button click by double-clicking on the «button1» in the designer.
C# program that uses OpenFileDialog using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // Show the dialog and get result. DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) // Test result. { } Console.WriteLine(result); // <-- For debugging use. } } }
The example demonstrates the use of the openFileDialog1 component that was created in the designer in previous steps. The DialogResult enumerated type is assigned to the result of ShowDialog.
Then: This DialogResult variable is tested to see what action the user specified to take.
DialogResult
Tip: The actual strings from the dialog window can be accessed directly as properties on openFileDialog1.
Read files. You can access the file specified by the user in the OpenFileDialog—and then read it in using the System.IO namespace methods. We also handle exceptions, preventing some errors related to file system changes that are unavoidable.
Note: In this example, when you click on the button the dialog will ask you what file you want.
And: When you accept the dialog, the code will read in that file and print its size in bytes.
C# program that reads in file from OpenFileDialog using System; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int size = -1; DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog. if (result == DialogResult.OK) // Test result. { string file = openFileDialog1.FileName; try { string text = File.ReadAllText(file); size = text.Length; } catch (IOException) { } } Console.WriteLine(size); // <-- Shows file size in debugging mode. Console.WriteLine(result); // <-- For debugging use. } } }
The event handler is executed when the user clicks on the button1 control. An OpenFileDialog is displayed. Second, the DialogResult is tested. Next the FileName property is accessed and the file is read in with File.ReadAllText.
Note: The above program for simplicity does not have a TextBox control to display the file it opens.
Tip: If you want to show the file contents in another control, add a TextBox and assign it to the text string.
Properties. The OpenFileDialog control in Windows Forms has many properties that you can set directly in the designer. You do not need to assign them in your own C# code. This section shows some notes on these properties.
AddExtension: You can change this to False from its default True if you want to automatically fix file extension problems.
AutoUpgradeEnabled: This allows you to automatically get Vista-style open file dialogs. Recommended. See blogs.msdn.com link.
AutoUpgradeEnabled for Open File Dialog
DefaultExt: Set this to a string extension for files to automatically add that extension. This is not often useful.
DereferenceLinks: This tells Windows to resolve shortcuts (aliases) on the system before returning the paths.
FileName: You can initialize this in the designer to a preset file name. This is changed to be the name the user specifies.
InitialDirectory: Specify a string to use that folder as the starting point. Try using Environment.SpecialFolder with this property.
Environment
Multiselect: Specifies if multiple files can be selected at once in the dialog. Users can select multiple files by holding SHIFT or CTRL.
Filters make it easier for the user to open a valid file. The OpenFileDialog supports filters for matching file names. The asterisk indicates a wildcard. With an extension, you can filter by a file type.
Filter: Use this to specify the file matching filter for the dialog box. With «C# files|*.cs», only files ending with «.cs» are shown.
FilterIndex: Use to specify the default filter, which will have index of 1. The second filter if one exists would have index of 2.
ValidateNames: The Windows file system does not allow files to contain characters such as «*». This option should usually be left as True.
ReadOnly. To continue, the OpenFileDialog has some properties that allow users to specify whether a file should be read in read-only mode. The read-only checkbox can be displayed. Usually these are not needed.
ReadOnlyChecked: This changes the default value of the «read only» checkbox, which is only shown when «ShowReadOnly» is set to True.
ShowReadOnly: Whether you want the read-only checkbox to be shown. If set to True, change «ReadOnlyChecked» to set the check state.
Summary. We looked at the useful OpenFileDialog in Windows Forms. Nearly every nontrivial program will need to have an open file dialog. This control implements this functionality without any problems.
And: We saw how to add an OpenFileDialog, set its properties, and use it in C# code.
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf
In a WinForms project, you can prompt the user to select a file by using the OpenFileDialog control:
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = openFileDialog.FileName;
}
Code language: C# (cs)
When you call ShowDialog(), it’ll prompt the user to select a file:
When the user clicks Open, you’ll be able to get the file path they selected from the OpenFileDialog.FileName property.
To use the OpenFileDialog control, drag it from the toolbox to the form. Then you can modify the properties through the UI or programmatically (as I’ll show in examples in this article).
The most important properties are InitialDirectory, Filter, and Multiselect. InitialDirectory is straightforward: when the prompt opens, it’ll open up to the specified initial directory. In this article, I’ll go into details about Filter and Multiselect properties, and then show an example of displaying the selected file’s metadata and content.
Filter which files can be selected
The Filter property controls which files appear in the prompt.
Here’s an example that only lets the user select .config and .json files:
openFileDialog.Filter = "Configuration files|*.config;*.json";
Code language: C# (cs)
Only .config and .json files will appear:
Filter string format
The filter string format is like this: <file group 1 name>|<file 1 name>;<file 2 name>|<file group 2 name>|<file 1 name><file 2 name>. This is a pretty confusing format, so it’s easier to just show examples.
Example – Only show a specific file
The following only allows the user to select a file with the name appsettings.json:
openFileDialog.Filter = "appsettings.json";
Code language: C# (cs)
Read more about how to read appsettings.json.
Example – Show all files
This allows the user to select any file:
openFileDialog.Filter = "All files|*.*";
Code language: C# (cs)
Example – Show a single file group with multiple extensions
This allows the user select any file with the .config or .json extensions:
openFileDialog.Filter = "Configuration files|*.config;*.json";
Code language: C# (cs)
The two extensions are grouped together and referred to as “Configuration files.”
Example – Show two file groups with one extension each
This allows the user to select a JSON or XML file:
openFileDialog.Filter = "XML|*.xml|JSON|*.json";
Code language: C# (cs)
Read more about parsing XML files.
The reason for having these two groups (XML and JSON) is because each group appears in the dropdown:
This is useful if you want to display names that are more specific to the extensions, instead of just using a generic group name like “Configuration files.”
Select multiple files
To allow the user to select multiple files, set Multiselect=true, and get all the files they selected from the OpenFileDialog.FileNames property:
openFileDialog.Multiselect = true;
openFileDialog.Filter = "Log files|*.log";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
foreach(var filePath in openFileDialog.FileNames)
{
//use file path
}
}
Code language: C# (cs)
This prompts the user to select a file. Since Multiselect is true, they can select multiple files at once:
When the user clicks Open, this’ll populate the OpenFileDialog.FileNames string array with all the file paths that the user selected.
Display the selected file’s metadata and contents
After the user picks a file, you can do any file operation you want. You’ll most likely want to read the file’s contents and metadata, as shown in this example:
using System.IO;
private void btnFilePicker_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Comma-separated values file|*.csv";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var filePath = openFileDialog.FileName;
txtFilePath.Text = filePath;
var fileInfo = new FileInfo(filePath);
var sb = new StringBuilder();
sb.AppendLine($"File name: {fileInfo.Name}");
sb.AppendLine($"Created At: {fileInfo.CreationTime}");
sb.AppendLine($"Modified At: {fileInfo.LastWriteTime}");
sb.AppendLine($"Bytes: {fileInfo.Length}");
txtFileInfo.Text = sb.ToString();
txtFileContent.Text = File.ReadAllText(filePath);
}
}
Code language: C# (cs)
Here’s what it looks like: