Basic operations for C # files and directories (System.IO)

Source: Internet
Author: User
Tags create directory

1. File operation

<summary>
File read and write operations
To simplify the code for everyone to learn, temporarily do not consider catching exceptions
</summary>
public partial class TestIO:DevComponents.DotNetBar.Office2007Form
{
    Public Testio ()
    {
        InitializeComponent ();
    }
    <summary>
    Create a file
    </summary>
    private void Btncreatefile_click (object sender, EventArgs e)
    {
        String path = Application.startuppath + @ "\test.txt";
        FileStream fs = new FileStream (path, filemode.create);
        StreamWriter SW = new StreamWriter (FS);
        Sw. WriteLine ("This is a test file.");
        Sw. WriteLine ("This was second line.");
        Sw. Close ();
        Fs. Close ();
        You can also create StreamWriter
        StreamWriter SW = file.createtext (path);
    }
    <summary>
    Read file
    </summary>
    private void Btnreadfile_click (object sender, EventArgs e)
    {
        String path = Application.startuppath + "\\Test.txt";
        Textboxx1.text = string. Empty;
        if (file.exists (path))
        {
            FileStream fs = new FileStream (path, FileMode.Open);
            StreamReader sr = new StreamReader (FS);
            You can also create StreamReader
            File.OpenText (path);
            String str = string. Empty;
            while (true)
            {
                str = Sr. ReadLine ();
                if (!string. IsNullOrEmpty (str))
                {
                    Textboxx1.text + = str + "\ r \ n";
                }
                Else
                {
                    Sr. Close ();
                    Fs. Close ();
                    Break
                }
            }
        }
        Else
        {
            MessageBox.Show ("This file does not exist under the specified path!");
        }
    }
    <summary>
    Append file contents
    </summary>
    private void Btnappendfile_click (object sender, EventArgs e)
    {
        String path = Application.startuppath + "\\Test.txt";
        FileStream fs = new FileStream (path, filemode.append);
        StreamWriter SW = new StreamWriter (FS);
        You can also create StreamReader
        StreamWriter SW = file.appendtext (path);
        Sw. WriteLine ("This was three line.");
        Sw. Close ();
        Fs. Close ();
    }
    <summary>
    Copying files
    </summary>
    private void Btncopyfile_click (object sender, EventArgs e)
    {
        String OldPath = Application.startuppath + "\\Test.txt";
        String NewPath = Application.startuppath + "\\TestClone.txt";
        File.Copy (OldPath, NewPath);
    }
    <summary>
    deleting files
    </summary>
    private void Btndeletefile_click (object sender, EventArgs e)
    {
        String path = Application.startuppath + "\\TestClone.txt";
        File.delete (path);
    }
    <summary>
    Moving files
    </summary>
    private void Btnmovefile_click (object sender, EventArgs e)
    {
        String OldPath = Application.startuppath + "\\Test.txt";
        You can also use a new file name while moving files
        String NewPath = "D:\\newtest.txt";
        File.move (OldPath, NewPath);
    }
    <summary>
    Create a Directory
    </summary>
    private void Btncreatedirectory_click (object sender, EventArgs e)
    {
        String path1 = "D:\\jason1";
        Create Directory Jason1
        DirectoryInfo dDepth1 = Directory.CreateDirectory (path1);
        DDepth2 points to subdirectories created by DDepth1 Jason2
        DirectoryInfo dDepth2 = ddepth1.createsubdirectory ("Jason2");
        Sets the directory to which the application's current working directory is dDepth2
        Directory.setcurrentdirectory (Ddepth2.fullname);
        Create a directory in the current directory Jason3
        Directory.CreateDirectory ("Jason3");
    }
    private void Btndeletedirectory_click (object sender, EventArgs e)
    {
        String path = "D:\\jason1";
        DeleteDirectory (path);
    }
    <summary>
    Delete the directory and all its subdirectories, file
    </summary>
    private static void DeleteDirectory (string path)
    {
        if (directory.exists (path))
        {
            foreach (String str in directory.getfilesystementries (path))
            {
                if (file.exists (str))
                {
                    File.delete (str);
                }
                Else
                {
                    DeleteDirectory (str);
                }
            }
            Directory.delete (path);
        }
        Else
        {
            MessageBox.Show ("The directory does not exist!");
        }
    }
    private void Btncopydirectory_click (object sender, EventArgs e)
    {
        String SourcePath = "D:\\jason1";
        String TargetPath = "D:\\jason2";
        CopyDirectory (SourcePath, TargetPath);
    }
    <summary>
    Copy the directory and all its contents
    </summary>
    <param name= "SourcePath" > Source directory </param>
    <param name= "TargetPath" > Target directory </param>
    private void CopyDirectory (String sourcepath, String TargetPath)
    {
        This character is used to separate the directory level in the path string that reflects the hierarchical File System Organization (MSDN)
        In the Windows system, it essentially adds "\ \" to the directory path.
        if (targetpath[targetpath.length-1]! = Path.directoryseparatorchar)
        {
            TargetPath + = Path.directoryseparatorchar;
        }
        The target directory does not exist and is created
        if (! Directory.Exists (TargetPath))
        {
            Directory.CreateDirectory (TargetPath);
        }
        Get file system (with directories and files)
        string[] fileList = directory.getfilesystementries (SourcePath);
        foreach (String fileName in FileList)
        {
            if (directory.exists (fileName))
            {
                Path.getfilename (filename) to remove the last hierarchical directory name or file name
                CopyDirectory (filename, TargetPath + path.getfilename (filename));
            }
            Else
            {
                True to overwrite
                File.Copy (filename, TargetPath + path.getfilename (filename), true);
            }
        }
    }
}

Basic operations for C # files and directories (System.IO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.