SoFunction
Updated on 2025-03-07

C# Download file Delete file Example of writing text

Since file processing is often used, I encapsulated it myself and shared it with everyone. Contains written text Batch delete file Download file. -- Can be used directly

/// <summary>
/// Write to txt/// </summary>
/// <param name="savePath"></param>
/// <param name="content"></param>
public static void WriteInTxt(string savePath, string content)
{
string tempPath = (savePath);
(tempPath); //Create temporary file directoryif (!(savePath))
{
FileStream fs1 = new FileStream(savePath, , );//Create a write fileStreamWriter sw = new StreamWriter(fs1);
(content);//Start write value();
();
}
else
{
FileStream fs = new FileStream(savePath, , );
StreamWriter sr = new StreamWriter(fs);
(content);//Start write value();
();
}
}
/// <summary>
/// Recursively delete all files in the folder/// </summary>
/// <param name="file"></param>
public static void DeleteFile(string dirPath)
{
try
{
//Remove read-only properties of folders and subfiles//Remove the read-only properties of the folder fileInfo = new DirectoryInfo(dirPath);
 =  & ;
//Remove the read-only attributes of the file(dirPath, );
//Judge whether the folder still existsif ((dirPath))
{
foreach (string f in (dirPath))
{
if ((f))
{
//If there is a subfile, delete the file(f);
}
else
{
//Recursively delete subfoldersDeleteFile(f);
}
}
//Delete empty folder(dirPath);
}
}
catch (Exception e)
{
}
}
/// <summary>
/// Http download file/// </summary>
/// <param name="url">Download file path</param>/// <param name="savePath">SavePath</param>/// &lt;returns&gt;&lt;/returns&gt;
public static bool HttpDownloadFile(string url, string savePath)
{
string tempPath = (savePath);
(tempPath); //Create temporary file directorystring tempFile = tempPath + @"\" + (savePath); //Temporary filesif ((tempFile))
{
// If there isreturn true;
//(tempFile); 
}
try
{
FileStream fs = new FileStream(tempFile, , , );
// Set parametersHttpWebRequest request = (url) as HttpWebRequest;
//Send a request and get the corresponding response dataHttpWebResponse response = () as HttpWebResponse;
//It is not until the () program starts sending Post requests to the destination webpageStream responseStream = ();
//Create a local file write stream//Stream stream = new FileStream(tempFile, );
byte[] bArr = new byte[1024];
int size = (bArr, 0, (int));
while (size &gt; 0)
{
//(bArr, 0, size);
(bArr, 0, size);
size = (bArr, 0, (int));
}
//();
();
();
(tempFile, savePath);
return true;
}
catch (Exception ex)
{
return false;
}
}

The above example of C# download file, delete file, and write text is all the content I share with you. I hope you can give you a reference and I hope you can support me more.