IOException when trying to delete an image - c#

I have a profile page where the user can change their profile picture, When the user clicks submit their old profile picture is delete and replace with a the new one. However, when I try and delete the image it gives the error below:
IOException: The process cannot access the file
'C:\Users\Shayan\source\repos\RestaurantWeb\RestaurantWeb\wwwroot\Images\Users\92487709-5b2f-417c-a64f-4661962693cf_imb5ohqzqr511.jpg'
because it is being used by another process.
Here is my snippet of code where I add and delete the images:
if (accountDetailsViewModel.ProfilePicture != null)
{
string fileName = FileUploadHelper.GetUniqueFileName(accountDetailsViewModel.ProfilePicture.FileName);
string filePath = FileUploadHelper.GetProfileFilePath(fileName, _webHostEnvironment);
await accountDetailsViewModel.ProfilePicture.CopyToAsync(new FileStream(filePath, FileMode.Create));
user.ProfileImagePath = fileName;
string previousImageFilePath = FileUploadHelper.GetProfileFilePath(accountDetailsViewModel.PreviousPicturePath, _webHostEnvironment);
if (System.IO.File.Exists(previousImageFilePath) && accountDetailsViewModel.PreviousPicturePath != "noprofilepic.jpeg")
{
System.IO.File.Delete(previousImageFilePath);
}
}
Why is this happening? Am I meant to be closing the file? I'm not using File.Create() so I can't really close it like:
var img = File.Create(filePath);
img.Close();

Try closing the FileStream that you're creating.
Edit: Check out this.

Related

StreamReader Could not find file (Because it is not being created)

I am trying to create a file for the further write to and read from.
I use Directory.CreateDirectory and File.Create but neither path nor file are being created.
On the Page which part I show here below I check if File exists, and if not, I create a File. On Second Page (that I dont show here) I add new lines to the file using StreamWrite. When saved, first Page comes to focus again and lists the content of the File(only one row in this study).
Here is my code for the part in question:
public async Task ReadFileAsync()
{
string directoryName = Path.GetDirectoryName(#"C:\Users\...\DataBase\");
Task.Run(async() => Directory.CreateDirectory(directoryName));
Task.Run(async() => File.Create(directoryName + "ProductsDatabase.txt"));
//code for reading from file
string path = (directoryName + "ProductsDatabase.txt");
using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))
{
ProductOneTextBlock.Text = ProductsDatabaseRead.ReadLine();
}
if (ProductOneTextBlock.Text == "")
{
ProductOneTextBlock.Text = "Nothing to show";
}
}
The file and folder are not being created.
I don't get any error.
I tried also different folders on the drive in case if there was READ ONLY folder in solution folder. No difference.
Anyone could help?
(I found many threads about this problem but here I cannot resolve it with none of the solutions.
Physical file is not being created.
When I attempt to write to it (from another page) I get error that the file could not be found(because it is not there indeed).
It seems that program loses itself somewhere between
Task.Run(async() => Directory.CreateDirectory(directoryName));
Task.Run(async() => File.Create(directoryName + "ProductsDatabase.txt"));
and:
using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))
{
ProductOneTextBlock.Text = ProductsDatabaseRead.ReadLine();
}
, as TextBlock is not being updated even if ProductsDatabaseRead is null.
If I put
ProductOneTextBlock.Text = "Nothing to show";
a the begining of the method, TextBlock gets updated.
SO, why the
using (StreamReader ProductsDatabaseRead = new StreamReader(File.OpenRead(path)))
does not work?
You're not waiting for Task.Run to complete. Your directory creation, file creation and attempt to open a "as you think newly created file" are out of order. That's why you're probably not able to open a file (it still does not exist at this point).
Task.Run returns a task that will be completed when the work is done. You need to wait for completion.
public void ReadFile()
{
string folderPath = #"C:\Users\patri\source\repos\DietMate\";
string fileName = "ProductsDatabase.txt";
string fullPath = Path.Combine(folderPath, fileName);
//insert code to check whether file exists.
// use Exists()
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
File.Create(fullPath);
}
//if yes, follow with code below
//insert code for reading from file
using (StreamReader ProductsDatabaseRead = new StreamReader(fullPath))
{
ProductTest.Text = ProductsDatabaseRead.ReadLine();
}
}

How can I open a specific text file without using OpenFileDialog?

I have a rich text editor that I have created in C#. One of the features I am now trying to add is templates. I do not want the user to have to use an OpenFileDialog to navigate to the template and open the file. I would like to specify the filepath myself so that the user only has to click one button in order to open the template.
Currently, I am trying to achieve this using the following code:
private void formalLetterToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
try
{
if (richTextBoxPrintCtrl1.Modified == true);
{
NewFile();
}
richTextBoxPrintCtrl1.Rtf = fileContents;
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
However, whenever I try to open the template, I get an exception that is as follows:
System.ArgumentsException: File format is not valid.
However, I have tried to open the file using my OpenFileDialog and that works fine. Could somebody assist me in getting this working correctly?
Your problem is that you're trying to convert the file to a string using str = fileStream.ToString(); however, this converts the filestream to a string which is not the same thing.
Instead just do string fileContents = File.ReadAllText(filepath); to get all of the files contents into a string. You only need to use a FileStream/StreamReader if you're going to do some type of processing on the file.
Also, your use of the FileStream is a little off. I think what you really want is a StreamReader with something like this (example from msdn);
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
A FileStream cannot be used to read a file. It must be passed to a StreamReader in order to actually read the file and in this case there is no point in doing that because there is an overload of the constructor which takes a filepath. It's only useful if you don't know what kind of stream the reader is going to be reading.
Where you have;
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
You actually just want thins line; string fileContents = File.ReadAllText(filepath); , nothing else. There is no need for a FileStream when you're just reading all the text into a string.
You are making very heavy weather of loading RTF. Your code to read a file into a string will never work, as #evanmcdonnal explained. Did your file dialog based code that succeeded really do it like that? Remember that a file dialog is just UI that generates a file name in a string. If your code with a file dialog works, then it will work when the file dialog is replaced with a hard coded string.
I suspect that some part of your problem is that you are using a relative path. Perhaps the working directory is not what you expect it to be. You should specify the full path to the file.
In any case, to load RTF simply call the LoadFile method of the control. But I strongly recommend passing the full path to the file.
richTextBoxPrintCtrl1.LoadFile(fullPathToRtfFile);

C# Save image without using Dialog

I am having trouble saving a user uploaded image to my "logos" file when the user presses "Save Team" on my form.
For you to get a taster of what the application does I have provided a screenshot here, upon pressing add team all the text box data is written to a text file and I want the image to automatically save into a predefined folder "logos", however I get the GDI++ error whenever I press save.
After reading through a few old threads on the web, I found that it could be caused by a few things such as file permissions, file size, the files name or even an open stream.
Below is the code I am currently using to save out my file which prompts the error:
private void btnAddTeam_Click(object sender, EventArgs e)
{
//VALIDATION FOR TEXT FILE AND OTHER STUFF HERE...
//SAVE THE IMAGE FILE
string filePath = picTeamLogo.ImageLocation;
Image tempImage = Image.FromFile(filePath);
tempImage.Save(#"../logos/");
}
If you are viewing the screenshot, please do not get confused by "arsenal.png" I am aware that that is not the full file path, its conversion is handled in another method, as only the filename is required to be written to the text file.
If anybody has any ideas on where I am going wrong then please point me in the right direction, vague errors such as the GDI one I just received are such a headache!
Alex.
Try this method
public void storeFile(FileUpload File, string dirName)
{
if (!Directory.Exists(MapPath("~/uploads/" + dirName)))
{
Directory.CreateDirectory(MapPath("~/uploads/" + dirName));
}
string saveLocation = MapPath("~/uploads/" + dirName + "/" + Path.GetFileName(File.FileName));
File.SaveAs(saveLocation);
}
that's because you have not specified the file name for save function !
take a look at this :
string filePath = picTeamLogo.ImageLocation;
FileInfo fi = new FileInfo(filePath);
Image tempImage = Image.FromFile(fi.FullName);
tempImage.Save(#"../logo/" + fi.Name);
now it works properly
See this earlier post of mine for similar issue...
A Generic error occurred in GDI+ in Bitmap.Save method
The stream remains locked - you can use memory stream as a temp location then save.
When either a Bitmap object or an Image object is constructed from a
file, the file remains locked for the lifetime of the object. As a
result, you cannot change an image and save it back to the same file
where it originated.
http://support.microsoft.com/?id=814675
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
tempImage.Save(memory, ImageFormat.Jpeg);
// memory.ToStream(fs) // I think the same
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
Or alternative is loading image via MemoryStream into the image - so the stream doesn't get locked in the first place...

The action can't be completed because the file is open in IIS Worker Process

I am uploading a image for a user & saving it on a specified location. The code is working fine in normal scenario i.e. user selects a image & save it, it works.
Challenge occurs when user selects a image( probably wrong image due to mistake) & don't save it, but again selects a new image & then saves it.
This scenario gives me the error :
"The process cannot access the file because it is being used by another process."
When I try to delete image from the location at the time of error, file can't be deleted with message:
"The action can't be completed because the file is open in IIS Worker Process
Close the file and try again."
Code is like this:
try
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
msf = new MemoryStream();
bytes=FileUpload1.FileBytes;
msf.Write(bytes, 0, bytes.Length);
using (FileStream stream = new FileStream(folder + "/" + filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
//converting any graphic file type to jpeg format
Image img = Image.FromStream(msf);
img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
msf.WriteTo(stream);
IsuploadSuccess = true;
img.Dispose();
}
}
catch
{
IsuploadSuccess = false;
}
finally
{
if (msf != null)
{
msf.Close();
msf.Dispose();
}
}
I have tried adding "FileAccess.ReadWrite" & "FileShare.ReadWrite" in file stream, but doesn't work either with all options in File stream.
Please help...
Instead of getting solution of problem, I finally change approach to get rid to source of challenge. I change file name with UserID (unique) appended with CurrentDateTime converted to string & store it to temp folder until user save the change. This forms a different file each time for the challenge scenario. After save each file in temp folder created by the user (preceded by unique userid) is deleted & last changes are saved to respective directory.
I had this problem and took me few hours to figure it out.
I my case the Bitmap new(path) had locked the file. I had to dispose of it before exiting the using block.
However it is the method by which I debugged it is important.
My approach in pinpointing the source of the problem was to open the folder where the image was saved and tracing the code line by line. After each line I deleted the file and did Ctrl+Z to put it back. If it gave an error when I tried to delete it, then that is the line that locked it. So I got to that line within 5 min.
using (MemoryStream memoryStream = new())
{
if (System.IO.File.Exists(path))
{
using(Bitmap bitmap = new(path)) <-- this solved it
{
ImageConverter imageConverter = new();
bitmap.Save(memoryStream, ImageFormat.Bmp);
bytes = memoryStream.ToArray();
}
}
}

Sharing violation during save as on Ubuntu Linux

I'm new to C# and I'm having a bit of an issue when saving to a new file. My program has two options for saving: save & save as.
I was getting a sharing violation error when saving, but I fixed that by closing the previous filestream. However, I still cant figure out why my save as code is giving me a sharing violation error.
Here's the code:
// get a file stream from the file chooser
FileStream file = File.OpenWrite(saveFc.Filename);
// check to see if the file is Ok
bool fileOk = file.CanWrite;
if (fileOk == true)
{
// get the filename
string filename = file.Name;
// store the filename for later use
UtilityClass.filename = filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// get a StreamWriter
StreamWriter writer = File.CreateText(filename);
// write to the file
writer.Write(text);
// close/save the file
writer.Close();
file.Close();
}
}
// close the file c
If you could help me figure it out that would be much appreciated. Thanks!
You're opening the same file twice:
FileStream file = File.OpenWrite(saveFc.Filename);
And:
string filename = file.Name;
StreamWriter writer = File.CreateText(filename);
Your code could probably be simplified to:
using (var writer = File.CreateText(saveFc.Filename))
{
// store the filename for later use
UtilityClass.filename = saveFc.Filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// write the text
writer.Write(text);
}
If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

Categories