So I am currently trying to figure out how I can download a file and then read it right after I download it.
My code downloads it, however when I try to use File.ReadAllText it does not allow me to read it as it says that it is being used by another process (FULL ERROR: "The process cannot access the file 'C:......\netcoreapp3.1\ver.txt' because it is being used by another process.')
I do not know exactly why this is being thrown and I would love to know why and how I can fix it. Thank you for your answers...
Code:
Download Method:
WebClient Client;
public void download(string url, string to)
{
Uri ur = new Uri(url);
File.Delete(to);
addAction("\nDownloading: " + url);
createFile(to.Substring(0, to.IndexOf(".")), "", to.Substring(to.IndexOf(".") + 1));
Client = new WebClient();
Client.DownloadProgressChanged += OnDownloadProgressChanged;
Client.DownloadFileCompleted += OnDownloadFileCompleted;
Client.DownloadFileAsync(ur, @"" + to);
}
Create File Method:
public void createFile(string name, string content, string type)
{
if (!(type == "") && File.Exists(name))
{
Console.WriteLine("This file already exists. Delete the file if you want to make a new one.");
return;
}
if (type == "" && Directory.Exists(name))
{
Console.WriteLine("This directory already exists. Delete the directory if you want to make a new one.");
return;
}
if (type.Equals(""))
{
//make a folder
Directory.CreateDirectory(name);
Console.WriteLine("Created the directory: " + name + "!");
}
else
{
//make a file.
using (FileStream fs = File.Create(@"" + name + "." + type))
{
byte[] title = new UTF8Encoding(true).GetBytes(content);
fs.Write(title);
fs.Close();
}
}
}
Run the download method and trying to access the file and read it:
download("somewebsite with a txt file", "ver.txt");
String ver = File.ReadAllText("Config/Other/ver.txt");
String curver = File.ReadAllText("ver.txt"); //error is here
File.Delete("ver.txt");