zoukankan      html  css  js  c++  java
  • Create, Read, Write, Copy, Move and Delete a Text File using C#

    In this article, we will explore some common text file operations using C#.

    This article has been requested by a long time reader of dotnetcurry.com. NET provides various classes like the File and FileInfo, to create, read, write and perform such similar operations on a text file. For example, you can use the Create() method of the File class to create a text file. The same could also be done using the CreateText() method of the FileInfo class. Similarly these classes also contain functionality to copy, move or delete a file. The trick is to find out when to use which class and for what purpose.

    The ‘File’ class contains static methods and performs security checks on all the methods. The FileInfo contains instance methods and security check is not necessary. So this method is useful if you plan to use the same instance of the class in multiple operations.

    However for copying, moving or deleting the files, the static methods are faster. Moreover, the Garbage Collector has less work to do when you use the File class, since the methods are static.

    For reading and writing text files, we have some abstract classes like the TextReader and TextWriter classes. There are some useful classes like the StreamReader, StringReader, StreamWriter and StringWriter that derive from these abstract classes.

    This article is by no means a comprehensive guide to demonstrate the capabilities of these classes. It should be treated as a ‘How do I’ kind of a series to demonstrate some of the capabilities of these classes. I will be giving some references at the end of this article, which should be read to gain a better understanding of these classes. Let us now see some code which demonstrates how to use these classes.

    Before you go ahead and use these methods, declare a class variable called ‘fileLoc’ which contains the filepath of the text file.

    C#

    string fileLoc = @"c:\sample1.txt";

    Create a Text File

    C#

    // Create a Text File

    private void btnCreate_Click(object sender, EventArgs e)

            {

    FileStream fs = null;

    if (!File.Exists(fileLoc))

                {

    using (fs = File.Create(fileLoc))

                    {

                    }

                }

            }

    Write to a Text File

    C#

    // Write to a Text File

    private void btnWrite_Click(object sender, EventArgs e)

            {

    if (File.Exists(fileLoc))

                {

    using (StreamWriter sw = new StreamWriter(fileLoc))

                    {

                        sw.Write("Some sample text for the file");                  

                    }

                }

            }

    Read From a Text File

    C#

    // Read From a Text File

    private void btnRead_Click(object sender, EventArgs e)

            {

    if (File.Exists(fileLoc))

                {

    using (TextReader tr = new StreamReader(fileLoc))

                    {

    MessageBox.Show(tr.ReadLine());

                    }

                }

            }

    Copy a Text File

    C#

    // Copy a Text File

    private void btnCopy_Click(object sender, EventArgs e)

            {

    string fileLocCopy = @"d:\sample1.txt";

    if (File.Exists(fileLoc))

                {

    // If file already exists in destination, delete it.

    if (File.Exists(fileLocCopy))

    File.Delete(fileLocCopy);

    File.Copy(fileLoc, fileLocCopy);

                }

            }

    Move a Text File

    C#

    // Move a Text file

    private void btnMove_Click(object sender, EventArgs e)

            {

    // Create unique file name

    string fileLocMove = @"d:\sample1" + System.DateTime.Now.Ticks + ".txt";

    if (File.Exists(fileLoc))

                {

    File.Move(fileLoc, fileLocMove);

                }

            }

    Delete a Text File

    C#

    // Delete a text file

    private void btnDelete_Click(object sender, EventArgs e)

            {

    if (File.Exists(fileLoc))

                {

    File.Delete(fileLoc);

                }

            }

    We saw how to achieve some of the most common requirements while dealing with text files. Take a look at these reference links below to get a detailed understanding of the File and FileInfo class.

    References :

    File Class

    FileInfo Class

    File System and Registry Guide

  • 相关阅读:
    超级好用的excel导出方法,比phpexcel快n倍,并且无乱码
    PHP生成随机数;订单号唯一
    php判断检测一个数组里有没有重复的值
    修改git 提交的用户名和用户Email命令
    利用 PHP CURL zip压缩文件上传
    Linux 重启 PHP-FPM 命令
    Postgresql 时间串转换格式
    rollup node.js 打包工具
    PHP正则表达式提取html超链接中的href地址
    解决Ubuntu系统下 mysql 远程连接失败的问题 ERROR 2003 (HY000): Can't connect to MySQL server on 'xxx.xxx.xx.xx' (110)
  • 原文地址:https://www.cnblogs.com/chenqingwei/p/1575106.html
Copyright © 2011-2022 走看看