C # Delete a single file or folder (permission modification)

Source: Internet
Author: User

After work the first technical blog, abstract some small technology, recorded.

Delete a single file directly with File.delete;

Delete Folder subfolders and subfolders with FileInfo and DirectoryInfo, the root directory first delete files, and then recursively into the subfolder. Note that the lack of permissions caused by the phenomenon can not be deleted, before the unification of the change to the normal property.


Clearsinglefile (); Cleardirectory ();


<summary>
Delete a single file
</summary>
static void Clearsinglefile ()
{
String i18n_file = Application.datapath + "/plugins/i18n.dll";//example, fill file absolute or relative path
Cleari18ndlls (I18n_file);
}


<summary>
Called by Clearsinglefile, function implementation
</summary>
static void Cleari18ndlls (String dllpath)
{
if (file.exists (DllPath))
{
Try
{
File.delete (DllPath);
}
catch (System.Exception ex)
{
Catch ex
}
}
}


<summary>
Delete folder and sub files
</summary>
static void Cleardirectory ()
{
String audiopath = Application.datapath + "/game/audio/resources";
Clearfileunderpath (audiopath);
}


<summary>
Called by Cleardirectory to delete all content under DataPath
</summary>
static void Clearfileunderpath (String datapath)
{
DirectoryInfo dir = new DirectoryInfo (datapath);


File
foreach (FileInfo fchild in dir.) GetFiles ("*"))//Here Optional file selection method
{
if (fchild.attributes!= fileattributes.normal)
Fchild.attributes = Fileattributes.normal; Avoid permissions problems when file properties are readonly or hidden
Fchild.delete ();
}


Folder
foreach (DirectoryInfo dchild in dir.) GetDirectories ("*"))//Here Optional folder filtering method
{
if (dchild.attributes!= fileattributes.normal)
Dchild.attributes = fileattributes.normal;//Avoid permissions problems when folder properties are readonly or hidden
Clearfileunderpath (dchild.fullname);//recursion
Dchild.delete ();
}
}

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.