Program saying file already in use but i closed it C# [duplicate] - c#

This question already has answers here:
Do I need to dispose the FileStream object?
(3 answers)
Closed 4 years ago.
private void buttonAdd_Click(object sender, EventArgs e)
{
string path = #"comics.txt";
if (!File.Exists(path))
{
var myComicsFile = File.Create(path);
myComicsFile.Close();
FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
TextWriter write = new StreamWriter(path);
}
else if (File.Exists(path))
{
FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
TextWriter write = new StreamWriter(path);
}
}
I keep getting the error System.IO.IOException: 'The process cannot access the file because it is being used by another process'
I thought I had fixed it by closing the file after i created it the opening it but i get the error still. Not sure what the correct solution is. Any help would be greatly appreciated.

Firstly, there is no need to create a file empty and open it, instead use the appropriate FileMode Instead
FileMode.OpenOrCreate
OpenOrCreate
Specifies that the operating system should open a file if it exists;
otherwise, a new file should be created. If the file is opened with
FileAccess.Read, Read permission is required. If the file access is
FileAccess.Write, Write permission is required. If the file is opened
with FileAccess.ReadWrite, both Read and Write permissions are
required.
When you use a BCL method always check the documentation for clues about how to use it, in-particular look for if something supports IDisposable if it does ALWAYS use a using statement when you can
using Statement (C# Reference)
Provides a convenient syntax that ensures the correct use of
IDisposable objects.
in short you could have just done this
using (var file = new FileStream("comics.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
using(var TextWriter write = new StreamWriter(file))
{
// stuff here
}
Basically, when using a using statement with a stream derivative, it closes and disposes any unmanaged resources like file handles. in your case, you have left the File Handle dangling and hence your problem

Use the “using” statement to ensure file is closed.
Reference:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

You can nest using to take away a lot of the potential problems (like you have experienced already) by automatically calling dispose. For example
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (System.IO.StreamReader sr = new StreamReader(bs))
{
string output = sr.ReadToEnd();
}
}
}

Related

Saving an ExcelPackage with exclusive lock of excel, giving error after opening excel file - C# - EPPlus

My objective is to write some data into an excel.
Here i am opening a file with file stream by exclusive lock (FileMode.Open, FileShare.Read etc., I need to lock the file to restrict others writing into excel while i am processing.) then writing some content into it and finally close the stream, so that other threads can write into this file. I am using EPPlus(5.7.4) version.
The code i am using here is :
public void WriteToExcel()
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var excelPackage = new ExcelPackage(stream))
{
DoSomething(excelPackage);
excelPackage.SaveAs(stream);
stream.Close();
}
}
public void DoSomething(ExcelPackage excelPackage)
{
var cell = excelPackage.Workbook.Worksheets[0].Cells[2, 3];
cell.Value = "some value";
}
I put a break point in using statement and opened excel in the middle of execution and it showing a message saying like below which is correct.
But once i finish with execution when i try to open excel file it showing below error message.
We found a problem with some content in Sample.xlsx. Do you want us to try to recover as much as we can? if you trust the source of this book, Click Yes
I tried in different ways but none worked for me, as same error message is displaying. Can someone help me resolving this issue.
The problem is that you're reading from and rewriting to the same file stream simultaneously.
You can test this by changing excelPackage.SaveAs(new FileInfo("Book2.xlsx")); and create a new file - your file will be created without any issues.
You could open your original document, write the changes to a new file, then delete the original file and rename the new file back to the original name:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var stream = new FileStream("Book1.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
using (var excelPackage = new ExcelPackage(stream))
{
DoSomething(excelPackage);
excelPackage.SaveAs(new FileInfo("Book2.xlsx"));
}
File.Delete("Book1.xlsx");
File.Move("Book2.xlsx", "Book1.xlsx");
The caveat with this is that if you have multiple things trying to access that file, then they might throw FileNotFound exceptions if they happen to try to open Book1.xlsx after it's delete and before Book2.xlsx is renamed.
That said, if you're dealing with that level of parallelism then you shouldn't be using a Excel file.
Side note: You don't need stream.Close(); as the using block automatically closes the stream.
Below code useful to me, you can refer it.
public void WriteToExcel()
{
string path = #"C:\Use**op\aa.xlsx";
FileInfo file = new FileInfo(path);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(file))
{
DoSomething(package);
}
}
public void DoSomething(ExcelPackage package)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
worksheet.Cells[2,4].Value = "some value";
package.Save();
}

How To "Unaccess" A File So Other Parts Of The Program Can Access It

I had the following code dispersed throughout my program. However I always seem to get the error below. Even though I am using a "using bracket" to dispose of resources I still don't know why this is happening.
Error:
The Process cannot access the file "the file path" because it is being used by another process.
Code:
string folderpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "AGoogleHistory");
string filecreate;
private void restoreTbasToolStripMenuItem_Click(object sender, EventArgs e)
{
using(StreamReader sr = new StreamReader(filecreate))
{
string s = sr.ReadToEnd();
MessageBox.Show(s, "History", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
try
{
browser.Navigate(new Uri(Address));
using(StreamWriter sw = new StreamWriter(filecreate))
{
sw.WriteLine(Address);
}
}
catch(System.UriFormatException)
{
return;
}
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are You Sure", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
File.Delete(filecreate);
}
else
{
}
}
I think you should first check that file is exists or not by
File.Exists(filePath);
Second thing you are passing wrong parameter to StreamReader class which is an empty string as you haven't assigned anything to it. Check above mentioned things first and you can refer below link for your ease :
The process cannot access file...
Let me know if you have any other issue after trying this.
StreamReader, by default, locks the file. This causes the error you are seeing. Luckily, StreamReader accepts a stream as one of it's overloads for it's constructor. This allows you to first create a FileStream, which has a handy enum allowing you to specify read/write sharing, then pass that FileStream to your StreamReader for use.
So in your case:
using(StreamReader sr = new StreamReader(filecreate))
...
becomes:
FileStream fs = new FileStream(filecreate, FileMode.Open, FileShare.ReadWrite);
using(StreamReader sr = new StreamReader(fs))
...
For more info, see the question below. It's essentially the same question, just asked differently. The accepted answer should explain a bit more.
How to open a StreamReader in ShareDenyWrite mode?
EDIT
Looking over your question again, I see that part of your problem is you don't close your streams. They should get closed when the using block exits, but it's best practice to close them yourself with sr.Close();
Also, you may need to add the delete flag to the fileshare option:
FileStream fs = new FileStream(filecreate, FileMode.Open, FileShare.ReadWrite|FileShare.Delete);
using(StreamReader sr = new StreamReader(fs))
...

Why is the file not opening?

I can't get the file to open.
private void button1_Click(object sender, EventArgs e)
{
// Load the CSV file
var lines = File.ReadAllLines(#"C:\chat.csv");
var xml = new XElement("Chat-Log", // To convert to XML
lines.Select(line => new XElement("Item",
line.Split('|') // indicate split
.Select((column, index) => new XElement("Column" + index, column)))));
xml.Save(#"C:\xml-out.xml"); // Save to XML file
MessageBox.Show("Converted to XML");
FileStream fileStream = new FileStream(#"c:\xmlout.xml", FileMode.Open);
try
{
TextWriter tw = new StreamWriter("c:\\xml-out.xml");
}
finally
{
fileStream.Close();
}
}
The above piece of code should open C:\xml-out.xml, right?
TextWriter tw = new StreamWriter("c:\\xml-out.xml");
I have no idea why it is not opening the file. Any clue?
I tried various options.
For some reason, you're opening a stream and then trying to create a writer for it.
If the file didn't exist before, then the call to new FileStream(#"c:\xmlout.xml", FileMode.Open) will throw an exception... and if the file did exist before, then you won't be able to open a writer to it in the following line because you've still got the file open for reading. You're also then closing the FileStream in the finally block, but never closing the StreamWriter, which is odd.
I expect you've probably got an exception showing which of those is actually causing the problem, but you should certainly remove the statement for the FileStream.
You should use a using statement so you don't need an explicit try/finally block:
using (StreamWriter writer = File.CreateText(#"c:\xml-out.xml"))
{
}
Of course there's then the possibility that you don't have permission to create a file on the root of the file system...

How can I find out why my XML file is already in use?

when I write the XML file to hard drive using the following code
XmlDocument doc = new XmlDocument();
doc.Load("D:\\project\\data.xml");
if (!Directory.Exists("D:\\project_elysian\\data\\" + System.DateTime.Today.ToString("dd-MM-yyyy")))
{
DirectoryInfo di = Directory.CreateDirectory("D:\\project_elysian\\data\\" + System.DateTime.Today.ToString("dd-MM-yyyy"));
}
XmlTextWriter writer = new XmlTextWriter("D:\\project_elysian\\data\\" + System.DateTime.Today.ToString("dd-MM-yyyy") + "\\" + System.DateTime.Now.ToString("HH-mm-ss") + ".xml", null);
XmlTextWriter writerlatest = new XmlTextWriter("D:\\project\\data\\latest\\today.xml", null);
writer.Formatting = Formatting.Indented;
writerlatest.Formatting = Formatting.Indented;
doc.Save(writer);
doc.Save(writerlatest);
doc = null;
writer.Flush();
writerlatest.Flush();
it writes the XML file as desired but after that when I try to read that XML file in the same asp.net page (code placed in a C# Code Behind file) using the following code, it gives an error
string filename = "D:\\project\\data\\latest\\today.xml";
XmlSerializer serializer = new XmlSerializer(typeof(searchResult));
serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
FileStream fs = new FileStream(filename, FileMode.Open);
the error is as follows
The process cannot access the file 'D:\project\data\latest\today.xml' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.IOException: The process cannot access the file 'D:\project\data\latest\today.xml' because it is being used by another process.
EDIT: The file isn't being used by any other process
Make sure you're closing your writer with a call like writer.Close();
The file is being used by yourself. You have to Close or dispose the XmlTextWriter object after using them.
public class XmlTextWriter : XmlWriter
{..}
public abstract class XmlWriter : IDisposable
{..}
implementing IDisposable tells user. I use some unmanaged resource please call Dispose to release them.  refer to msdn: IDisposable Interface
A shortcut is using which provides a convenient syntax that ensures the correct use of IDisposable objects. for example:
using (System.IO.FileStream fs =
new System.IO.FileStream("c:\\file.txt",
System.IO.FileMode.Open),
fs2 =
new System.IO.FileStream("c:\\file2.txt",
System.IO.FileMode.CreateNew))
{
// do something here
}
Above code comes from: DISPOSE WITH USING
You need to close the file as you open using xmlwriter, it doesn't close the file automatically. In simple words if your file is open using other process you can't open it again till that file closed manually using your code.

How to get a file and move it out of the isolated storage?

I want to take a file that stored already in the isolated storage, and copy it out, somewhere on the disk.
IsolatedStorageFile.CopyFile("storedFile.txt","c:\temp")
That doesn't work. Throws IsolatedStorageException and says "Operation not permitted"
I don't see anything in the docs, other than this, which just says that "Some operations aren't permitted", but doesn't say what, exactly. My guess is that it doesn't want you copying out of isolated storage to arbitrary locations on disk. The docs do state that the destination can't be a directory, but even if you fix that, you still get the same error.
As a workaround, you can open the file, read its contents, and write them to another file like so.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
{
//write sample file
using (Stream fs = new IsolatedStorageFileStream("test.txt", FileMode.Create, store))
{
StreamWriter w = new StreamWriter(fs);
w.WriteLine("test");
w.Flush();
}
//the following line will crash...
//store.CopyFile("test.txt", #"c:\test2.txt");
//open the file backup, read its contents, write them back out to
//your new file.
using (IsolatedStorageFileStream ifs = store.OpenFile("test.txt", FileMode.Open))
{
StreamReader reader = new StreamReader(ifs);
string contents = reader.ReadToEnd();
using (StreamWriter sw = new StreamWriter("nonisostorage.txt"))
{
sw.Write(contents);
}
}
}

Categories

Resources