Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Winform to realize file operation in C #

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the C # how to develop Winform to achieve file operation related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this C# how to develop Winform to achieve file operation article will have a harvest, let's take a look at it.

1. File dialog box

C# has three file dialogs, which are used for different functions:

(1) the dialog box OpenFileDialog used to open the file.

(2) the dialog box SaveFileDialog used to save the file.

(3) Open the dialog box FolderBroswerDialog of the folder.

Example: as shown in the following figure, click three buttons to pop up three dialogs, and after performing the corresponding actions, the path is displayed in the text box:

(1) OpenFileDialog dialog box

Change the Name property of the OpenFileDialog dialog box to ofDlg. Add ofDlg.ShowDialog () to the Open button; the interface is as follows:

By the return value of ShowDialog (), you can determine whether you clicked "open" or "cancel". Write the following code in the Open button click event:

Private void btnOpen_Click (object sender, EventArgs e) {/ / determine whether to click the "open" button if (ofDlg.ShowDialog () = = DialogResult.OK) {txtPath.Text = ofDlg.FileName;}}

OpenFileDialog Common property sheet:

The property name function describes the initial directory Filter file filter of the InitialDirectory dialog box, which is written in the format "display name | Type", for example, "text files (.txt) | .txt | all files (.) | |." the index of the file filter selected by FilterIndex in the dialog box. If you select the first item, set it to 1FileName the first file displayed in the dialog box or the last selected file Title will display the character CheckFileExists in the title bar of the dialog box whether a warning CheckPathExists is displayed when the user specifies a file that does not exist before the dialog box returns, check whether the specified path exists (2) SaveFileDialog dialog box

The Save File dialog box is often used for the Save as function in software. Its common properties, methods, and usage are the same as the open file dialog box.

Set the Filter property of the save file dialog box to text file | * .txt. Write the following code in the click event of the Save button:

Private void btnSave_Click (object sender, EventArgs e) {if (sfDlg.ShowDialog () = = DialogResult.OK) {txtPath.Text = sfDlg.FileName;}} (3) FolderBroswerDialog dialog box

The Browse for folder dialog box is often used to browse the folder and select the folder path.

Write the following code in the click event of the Browse button:

Private void btnBrowse_Click (object sender, EventArgs e) {if (fbDlg.ShowDialog () = = DialogResult.OK) {txtPath.Text = fbDlg.SelectedPath;}}

FolderBroswerDialog common properties:

The property name can describe the string that Description displays above the tree view of the dialog box, which is used to specify the guidance information displayed to the user. RootFolder sets root folder location SelectedPath dialog box whether the first selected folder or the last selected folder full path ShowNewFold dialog box includes the "New folder" button 2, files and folder operations.

File and folder management is an important part of the operating system, which mainly includes create, move, copy and delete operations.

The Directory class and the DirectoryInfo class are used to manage the operation of disks and folders.

The File class and the FileInfo class are used to manage common operations on files.

(1) Common operations of files

The File class is generally used in C # for minor operations such as creating, copying, and deleting files.

The File class is a static class, where all methods are static and are called directly through the class name without instantiation.

An example, as shown in the following figure, performs the basic operation of the file:

Click the Select File button to select a file and display the file path in the text box.

Click the Select folder button to select a folder and display the folder path in the text box.

Click the "copy File" button to copy the file to the folder.

Click the "move File" button to move the file to a folder.

Click the "Delete File" button to delete the file.

Among them, "Select file" button name=btOpenFile, "select folder" button name=btOpenFolder, "copy file" button name=btCopy, "move file" button name=btMove, "delete file" button name=btDelete.

The text box name=txtFile for the file name and the text box name=txtFolder for the folder name.

File dialog box name=openFileDialog1, folder dialog box name=folderBrowserDialog1.

The File class implementation code is as follows:

/ / Select the file button private void btOpenFile_Click (object sender, EventArgs e) {if (this.openFileDialog1.ShowDialog () = = DialogResult.OK) {/ / FileName contains the path, SafeFileName does not contain the path this.txtFile.Text = this.openFileDialog1.FileName }} / / Select folder button private void btOpenFolder_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder.Text = this.folderBrowserDialog1.SelectedPath;}} / / copy file button private void btCopy_Click (object sender, EventArgs e) {if (! File.Exists (this.txtFile.Text)) {MessageBox.Show ("File does not exist!"); return } if (! Directory.Exists (this.txtFolder.Text)) {MessageBox.Show ("folder does not exist!"); return;} string [] arrName = this.txtFile.Text.Split ('\\'); string name = arrName [arrName.Length-1] / / the third parameter true represents a direct overwrite of the file / / if you do not want to overwrite, add the code here to determine that the file already exists and give a prompt File.Copy (this.txtFile.Text, this.txtFolder.Text + "\\" + name,true); MessageBox.Show ("copy successful!") } / / move the file private void btMove_Click (object sender, EventArgs e) {if (! File.Exists (this.txtFile.Text)) {MessageBox.Show ("File does not exist!"); return;} if (! Directory.Exists (this.txtFolder.Text)) {MessageBox.Show ("folder does not exist!"); return } string [] arrName = this.txtFile.Text.Split ('\\'); string name = arrName [arrName.Length-1]; string newFileName = this.txtFolder.Text + "\\" + name; if (File.Exists (newFileName)) {/ / option 1: prompt the user to have a duplicate file / / MessageBox.Show ("there is a file with the same name in the target location!"); / / return / / option 2: delete the target file directly File.Delete (newFileName);} File.Move (this.txtFile.Text, newFileName); MessageBox.Show ("move successfully!");} / / delete the file private void btDelete_Click (object sender, EventArgs e) {if (! File.Exists (this.txtFile.Text)) {MessageBox.Show ("File does not exist!"); return } File.Delete (this.txtFile.Text); MessageBox.Show ("deleted successfully!");}

Compared with the FileInfo class, using the File class avoids the overhead of frequently creating and releasing objects, but if you need to reuse a file object multiple times, use the FileInfo class.

The following uses the FileInfo class to implement the same function, as follows:

/ / Select the file button private void btOpenFile_Click (object sender, EventArgs e) {if (this.openFileDialog1.ShowDialog () = = DialogResult.OK) {/ / FileName contains the path, SafeFileName does not contain the path this.txtFile.Text = this.openFileDialog1.FileName }} / / Select folder button private void btOpenFolder_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder.Text = this.folderBrowserDialog1.SelectedPath;}} / / copy the file private void btCopy_Click (object sender, EventArgs e) {FileInfo fInfo = new FileInfo (this.txtFile.Text); if (fInfo.Exists = = false) {MessageBox.Show ("File does not exist!") Return;} DirectoryInfo dInfo = new DirectoryInfo (this.txtFolder.Text); if (dInfo.Exists = = false) {MessageBox.Show ("folder does not exist!"); return;} string [] arrName = this.txtFile.Text.Split ('\'); string name = arrName [arrName.Length-1] / / the second parameter true represents the existence of direct overwrite fInfo.CopyTo (this.txtFolder.Text + "\\" + name, true); MessageBox.Show ("copy successful!");} / / move file private void btMove_Click (object sender, EventArgs e) {FileInfo fInfo = new FileInfo (this.txtFile.Text); if (fInfo.Exists = = false) {MessageBox.Show ("File does not exist!"); return } DirectoryInfo dInfo = new DirectoryInfo (this.txtFolder.Text); if (dInfo.Exists = = false) {MessageBox.Show ("folder does not exist!"); return;} string [] arrName = this.txtFile.Text.Split ('\\'); string name = arrName [arrName.Length-1]; string newFileName = this.txtFolder.Text + "\\" + name; FileInfo deskFile = new FileInfo (newFileName) If (deskFile.Exists = = true) {/ / scenario 1: prompt the user to have a file with the same name / / MessageBox.Show ("there is a file with the same name in the target location!"); / / return; / / option 2: delete the target file directly deskFile.Delete ();} fInfo.MoveTo (newFileName); MessageBox.Show ("move successfully!") } / / Delete files private void btDelete_Click (object sender, EventArgs e) {FileInfo fInfo = new FileInfo (this.txtFile.Text); if (fInfo.Exists = = false) {MessageBox.Show ("File does not exist!"); return;} fInfo.Delete (); MessageBox.Show ("deleted successfully!");} (2) Common folder operations

The Directory class is a static class, where all methods are static and are called directly through the class name.

An example, such as the following figure, performs the basic operation of a folder:

Click the "Select folder one" button, select the folder, and display the folder path in the first text box.

Click the "Select folder 2" button, select the folder, and display the folder path in the second text box.

Click the move folder button to move the folder of the first text box path to the folder of the second text box path.

Click the "Delete folder" button to delete the folder in the path of the first text box.

Among them, "Select folder 1" button name=btOpen1, "Select folder 2" button name=btOpen2, "move folder" button name=btMove, "delete folder" button name=btDelete.

The first text box name=txtFolder1, the second text box name=txtFolder2.

File dialog box name=openFileDialog1, folder dialog box name=folderBrowserDialog1.

The Directory implementation code is as follows:

/ / Select a folder-private void btOpen1_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder1.Text = this.folderBrowserDialog1.SelectedPath;}} / / Select a folder-private void btOpen2_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder2.Text = this.folderBrowserDialog1.SelectedPath }} / / move folder private void btMove_Click (object sender, EventArgs e) {if (! Directory.Exists (this.txtFolder1.Text) | |! Directory.Exists (this.txtFolder2.Text)) {MessageBox.Show ("folder does not exist!"); return;} / / get folder name string [] arrFolderName = this.txtFolder1.Text.Split ('\\'); string folderName = arrFolderName [arrFolderName.Length-1] String newFolderName = this.txtFolder2.Text + "\\" + folderName; / / determine whether the destination address already has the folder if (Directory.Exists (newFolderName)) {/ / option 1: give a prompt / / MessageBox.Show ("at the target location, the folder already exists"); / / return / / Scheme 2: delete the folder Directory.Delete (newFolderName,true) in the target location;} / / this move operation can only operate Directory.Move (this.txtFolder1.Text, newFolderName) on the same root drive letter; MessageBox.Show ("move folder successfully!") } private void btDelete_Click (object sender, EventArgs e) {if (! Directory.Exists (this.txtFolder1.Text)) {MessageBox.Show ("folder does not exist!"); return;} / / the second parameter represents deletion of all subfolders and files Directory.Delete (this.txtFolder1.Text, true); MessageBox.Show ("folder deleted successfully!");}

Similarly, the above functions are implemented using DirectoryInfo as follows:

/ / Select a folder-private void btOpen1_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder1.Text = this.folderBrowserDialog1.SelectedPath;}} / / Select a folder-private void btOpen2_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder2.Text = this.folderBrowserDialog1.SelectedPath }} / / move folder private void btMove_Click (object sender, EventArgs e) {DirectoryInfo startInfo = new DirectoryInfo (this.txtFolder1.Text); DirectoryInfo endInfo = new DirectoryInfo (this.txtFolder2.Text); if (startInfo.Exists = = false | | endInfo.Exists = = false) {MessageBox.Show ("folder does not exist"); return;} string [] arrFolderName = this.txtFolder1.Text.Split ('\\') String folderName = arrFolderName [arrFolderName.Length-1]; string newFolderName = this.txtFolder2.Text + "\\" + folderName; / / to determine whether the destination address already has the folder DirectoryInfo tmp = new DirectoryInfo (newFolderName); if (tmp.Exists = = true) {/ / option 1: give a prompt / / MessageBox.Show ("at the target location, the folder already exists"); / / return / / Scheme 2: delete the folder tmp.Delete (true) in the target location;} / / this move operation can only operate startInfo.MoveTo (newFolderName) on the same root drive letter; MessageBox.Show ("move successfully!") ;} private void btDelete_Click (object sender, EventArgs e) {DirectoryInfo startInfo = new DirectoryInfo (this.txtFolder1.Text); if (startInfo.Exists = = false) {MessageBox.Show ("folder does not exist"); return;} / / parameter represents deletion of all subfolders and files startInfo.Delete (true); MessageBox.Show ("folder deleted successfully!");} (3) folder replication and movement

With regard to the movement of folders, the functions provided to us by the system can only be operated on the same root drive.

With regard to folder replication, the system does not provide a corresponding API at all.

So you can only write about the replication of folders and the movement of files across the disk, and you can implement it yourself, as shown in the figure:

Click the "Select folder one" button: you can select a folder and display the path of the folder in the first text box.

Click the "Select folder 2" button: you can select a folder and display the path of the folder in the second text box.

Click the "copy folder" button: copy the first folder and its contents to the second folder.

Click the "move folder" button: move the first folder and its contents to the second folder.

Among them: "Select folder 1" button name=btOpen1, "Select folder 2" button name=btOpen2, "copy folder" button name=btCopy, "move folder" button name=btMove.

The first text box name=txtFolder1, the second text box name=txtFolder2.

File dialog box name=openFileDialog1, folder dialog box name=folderBrowserDialog1.

The specific implementation code is as follows:

Write a general recursive method to copy folders:

/ / endFolderPath is the target path after processing / / for example, if "C:\ abc" is copied to "private void CopyFolder 123\ abc" after processing, endFolderPath needs to pass the processed "Drang123\ abc" private void CopyFolder (string startFolderPath, string endFolderPath) {/ / creating the destination folder Directory.CreateDirectory (endFolderPath); DirectoryInfo startDir = new DirectoryInfo (startFolderPath) / / copy all files under the folder foreach (FileInfo item in startDir.GetFiles ()) {File.Copy (item.FullName, endFolderPath + "\\" + item.Name);} / / Loop all subfolders to form a recursive call to foreach (DirectoryInfo item in startDir.GetDirectories ()) {string startPath = item.FullName; string newFolderName = endFolderPath + "\" + item.Name CopyFolder (startPath, newFolderName);}}

The code for each button is as follows:

Private void btOpen1_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder1.Text = this.folderBrowserDialog1.SelectedPath;}} private void btOpen2_Click (object sender, EventArgs e) {if (this.folderBrowserDialog1.ShowDialog () = = DialogResult.OK) {this.txtFolder2.Text = this.folderBrowserDialog1.SelectedPath }} / / copy folder private void btCopy_Click (object sender, EventArgs e) {if (! Directory.Exists (this.txtFolder1.Text) | |! Directory.Exists (this.txtFolder2.Text)) {MessageBox.Show ("folder does not exist!"); return;} string [] arrFolderName = this.txtFolder1.Text.Split ('\\'); string folderName = arrFolderName [arrFolderName.Length-1] String newFolderName = this.txtFolder2.Text + "\\" + folderName; / / determine whether the destination address already has the folder if (Directory.Exists (newFolderName)) {/ / option 1: give a prompt / / MessageBox.Show ("at the target location, the folder already exists"); / / return / / scenario 2: delete the folder Directory.Delete (newFolderName, true) in the target location;} CopyFolder (this.txtFolder1.Text, newFolderName); MessageBox.Show ("copy successful!") } / / move folder private void btMove_Click (object sender, EventArgs e) {if (! Directory.Exists (this.txtFolder1.Text) | |! Directory.Exists (this.txtFolder2.Text)) {MessageBox.Show ("folder does not exist!"); return;} string [] arrFolderName = this.txtFolder1.Text.Split ('\\'); string folderName = arrFolderName [arrFolderName.Length-1] String newFolderName = this.txtFolder2.Text + "\\" + folderName; / / determine whether the destination address already has the folder if (Directory.Exists (newFolderName)) {/ / option 1: give a prompt / / MessageBox.Show ("at the target location, the folder already exists"); / / return / / option 2: delete the folder Directory.Delete (newFolderName, true) in the target location;} CopyFolder (this.txtFolder1.Text, newFolderName); / / delete the folder Directory.Delete (this.txtFolder1.Text, true) in the original location after the replication is completed; MessageBox.Show ("move successfully!");} III. The concept of reading and writing text files and streams:

A file is an ordered collection of data permanently stored on various media. It is the basic object for data reading and writing.

A stream is a way to read and write bytes to memory, and it is also a basic object for data read and write operations.

Streams provide continuous byte stream storage space, and their actual storage locations can be discontinuous.

All classes that represent streams in C # inherit from the abstract class Stream.

The most common classes for reading and writing text files are:

-- FileStream (file stream)

-- StreamReader (stream reader)

-- StreamWriter (stream writer)

The basic steps for reading and writing files are:

Create a file stream

Create a reader and writer

Perform read and write operations

Turn off the reader

Close the file stream

File stream object:

The syntax of the instantiated file stream object is as follows:

FileStream fs = new FileStream (FileName, FileMode,FileAccess)

The enumerated values of FileMode are as follows:

The value name function indicates that CreateNew creates a new file, throws an exception Create to create a new file if the file already exists, overrides the Open to open the file if the file already exists, throws an exception OpenOrCreate to open the file if the file does not exist, creates a new file Append opens the file and finds the tail of the file, creates a new file Truncate opens the current file and clears its contents if the file does not exist, and throws an exception if the file does not exist

The enumerated values of FileAccess are as follows:

The value name function describes Read read-only access to files Write write-only access to files ReadWrite read-write access to files commonly used by file readers:

Common methods of StreamReader:

The value name function tells Read to read the next (group) character in the input stream ReadLine reads a line of characters in the current stream, returns the data as a string to ReadToEnd to read all characters from the current position to the end, and returns the data as a string to Close to close the StreamReader object and the underlying stream and release all system resources associated with the reader

Common methods of StreamWriter:

The value name function indicates that Write writes data to the stream WriteLine writes data before the line Terminator to the stream Close closes the StreamWriter object and the underlying stream

Example: write a text file reader as shown below

Click the "Open File" button, select a text file, and display the text file path in the single-line text box above, and the contents of the text file in the multi-line text box below.

Multi-line text box, whose text content can be modified.

Click the "Save File" button to save the text of the multiline text box to the open text file.

Among them, "Open File" button name=btOpen, "Save File" button name=btSave, single-line text box name=txtFilePath, multi-line text box name=txtContent.

The implementation code is as follows:

Private void btOpen_Click (object sender, EventArgs e) {OpenFileDialog dialog = new OpenFileDialog (); DialogResult result = dialog.ShowDialog (); / / if (result = = System.Windows.Forms.DialogResult.OK) {this.txtFilePath.Text = dialog.FileName;} else {return after clicking the open button } / / scenario 1: use Filestream to convert all the text into a byte array at once, and then convert it to string / / FileStream fs = new FileStream (this.txtFilePath.Text, FileMode.Open, FileAccess.Read); / fs.Seek (0, SeekOrigin.Begin); / / Positioning stream, moving 0 bytes from the start position, that is, the very beginning position of the stream / / int len = (int) fs.Length / / get the byte length of the file / / byte [] arrByte = new byte [len]; / / define the byte array / / fs.Read (arrByte,0, arrByte.Length); / / read the file stream into the byte array / / this.txtContent.Text = Encoding.Default.GetString (arrByte,0,len); / / fs.Close () / / Scheme 2: use Filestream to read the text byte by byte, then convert the byte to string / / FileStream fs = new FileStream (this.txtFilePath.Text, FileMode.Open, FileAccess.Read); / / int len = (int) fs.Length; / / get the byte length of the file / / byte [] arrByte = new byte [len]; / / define the byte array / / int index = 0 / / Save the subscript of the byte array change / / int code = fs.ReadByte (); / / read a byte / / while (code! =-1) / / read equal to-1 means that the read is completed / / {/ convert the read to a byte array / / arrByte [index] = Convert.ToByte (code); / / code = fs.ReadByte () / / continue reading byte by byte / / index++; / /} / / this.txtContent.Text = Encoding.Default.GetString (arrByte, 0, len); / / fs.Close () / / Scheme 3: directly use the ReadAllText function of File to read all the contents of the text file into text / / File.ReadAllBytes can be read into a byte array / / this.txtContent.Text = File.ReadAllText (this.txtFilePath.Text, Encoding.Default); / / scenario 4: use StreamReader stream reader to read FileStream fs = new FileStream (this.txtFilePath.Text, FileMode.Open, FileAccess.Read) StreamReader sd = new StreamReader (fs, Encoding.Default); / / you can read / / string line = sd.ReadLine () line by line here; / / while (line! = null) / / {/ / this.txtContent.Text = this.txtContent.Text + line + "\ r\ n"; / / line = sd.ReadLine (); / /} / / you can also read all this.txtContent.Text = sd.ReadToEnd () Sd.Close (); fs.Close ();} private void btSave_Click (object sender, EventArgs e) {/ / scenario 1: File class static methods / / File.WriteAllText (this.txtFileName.Text, this.txtContent.Text,Encoding.Default); / / MessageBox.Show ("saved successfully!") / / scenario 2: use the StreamWriter stream writer FileStream fs = new FileStream (this.txtFileName.Text, FileMode.Open, FileAccess.Write); StreamWriter sw = new StreamWriter (fs, Encoding.Default); sw.Write (this.txtContent.Text); sw.Close (); fs.Close (); MessageBox.Show ("saved successfully!") Serialization and deserialization

Serialization is the process of storing the state of an object instance to a storage medium.

Implementation steps for serialization and deserialization (binary serialization):

(1) introduce System.Runtime.Serialization.Formatters.Binary namespace

(2) the object to be serialized needs to be marked with the Serializable attribute

(3) reference types in its parent class and attributes are also marked with Serializable attributes

(4) use the Serialize () method and Deserialize () method of the BinaryFormatter object

(1) serialize a single object

Example: as shown in the following figure, serialization and deserialization of a single object

Enter the student information and click the "Save Information" button to permanently serialize the student information to the computer.

After closing the program, after starting the program, you can read the local serialization file and display the information in the text box of the interface.

Among them, the name of the text box of student number, name and age is txtNo,txtName,txtAge.

The name buttons for save and read information are btSave and btRead, respectively.

The specific implementation code is as follows:

Define a student class:

[Serializable] class Student {public string StuNo {get; set;} / / Student ID public string StuName {get; set;} / / name public int StuAge {get; set;} / / Age}

The [Serializable] keyword means that this class can be serialized.

Write the button response event code:

Private void btSave_Click (object sender, EventArgs e) {Student stu = new Student (); stu.StuNo = this.txtNo.Text; stu.StuName = this.txtName.Text; stu.StuAge = int.Parse (this.txtAge.Text); FileStream fs = new FileStream ("stu.ini", FileMode.Create, FileAccess.ReadWrite); BinaryFormatter bf = new BinaryFormatter (); bf.Serialize (fs, stu); / / serialize fs.Close () MessageBox.Show ("saved successfully!");} private void btRead_Click (object sender, EventArgs e) {FileStream fs = new FileStream ("stu.ini", FileMode.Open, FileAccess.ReadWrite); BinaryFormatter bf = new BinaryFormatter (); Student stu = bf.Deserialize (fs) as Student; / / deserialized this.txtNo.Text = stu.StuNo; this.txtName.Text = stu.StuName; this.txtAge.Text = stu.StuAge.ToString (); fs.Close () } (2) serialize the collection

Example: serialize the collection as shown in the following figure

Open the form, automatically read the information from the serialized file, and display it on the listView list.

Enter student information, click the "add Information" button, add students, and serialize the student list, refresh the ListView list data.

The name=listView1 of the ListView control that displays the list.

The name of the text box of student number, name and age is txtNo,txtName,txtAge, respectively.

Add information button name=btSave.

The specific implementation code is as follows:

Define a student class:

[Serializable] class Student {public string StuNo {get; set;} / / Student ID public string StuName {get; set;} / / name public int StuAge {get; set;} / / Age}

The [Serializable] keyword means that this class can be serialized.

Write the button response event code:

List list = new List (); private void BindData () {if (! File.Exists ("list.ini")) return; / / read serialization file FileStream fs = new FileStream ("list.ini", FileMode.Open, FileAccess.ReadWrite); BinaryFormatter bf = new BinaryFormatter (); list = bf.Deserialize (fs) as List; / / deserialize fs.Close () / / bind list collection data to ListView controls this.listView1.Items.Clear (); foreach (Student stu in list) {ListViewItem item = new ListViewItem (stu.StuNo); item.SubItems.Add (stu.StuName); item.SubItems.Add (stu.StuAge.ToString ()); this.listView1.Items.Add (item);} private void Form2_Load (object sender, EventArgs e) {BindData () } private void btSave_Click (object sender, EventArgs e) {Student stu = new Student (); stu.StuNo = this.txtNo.Text; stu.StuName = this.txtName.Text; stu.StuAge = int.Parse (this.txtAge.Text); list.Add (stu); FileStream fs = new FileStream ("list.ini", FileMode.Create, FileAccess.ReadWrite); BinaryFormatter bf = new BinaryFormatter (); bf.Serialize (fs, list); / / serialized fs.Close () MessageBox.Show ("saved successfully!"); BindData ();} this article on "how to develop Winform to operate files in C #" ends here. Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to develop Winform to achieve file operation". 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report