Baca dalam bahasa Inggris

Bagikan melalui


FileInfo.Delete Metode

Definisi

Menghapus file secara permanen.

public override void Delete ();

Pengecualian

File target terbuka atau dipetakan memori di komputer yang menjalankan Microsoft Windows NT.

-atau-

Ada handel terbuka pada file, dan sistem operasinya adalah Windows XP atau yang lebih lama. Handel terbuka ini dapat dihasilkan dari menghitung direktori dan file. Untuk informasi selengkapnya, lihat Cara: Menghitung Direktori dan File.

Pemanggil tidak memiliki izin yang diperlukan.

Jalurnya adalah direktori.

Contoh

Contoh berikut menunjukkan Delete metode .

using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        string path = @"c:\MyTest.txt";
        FileInfo fi1 = new FileInfo(path);

        try
        {
            using (StreamWriter sw = fi1.CreateText()) {}
            string path2 = path + "temp";
            FileInfo fi2 = new FileInfo(path2);

            //Ensure that the target does not exist.
            fi2.Delete();

            //Copy the file.
            fi1.CopyTo(path2);
            Console.WriteLine("{0} was copied to {1}.", path, path2);

            //Delete the newly created file.
            fi2.Delete();
            Console.WriteLine("{0} was successfully deleted.", path2);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.

Contoh berikut membuat, menutup, dan menghapus file.

using System;
using System.IO;

public class DeleteTest
{
    public static void Main()
    {
        // Create a reference to a file.
        FileInfo fi = new FileInfo("temp.txt");
        // Actually create the file.
        FileStream fs = fi.Create();
        // Modify the file as required, and then close the file.
        fs.Close();
        // Delete the file.
        fi.Delete();
    }
}

Keterangan

Jika file tidak ada, metode ini tidak melakukan apa-apa.

Berlaku untuk

Produk Versi
net-8.0 net-8.0

Lihat juga