IO Exception in C# - c#

In my c# application which developed with c# in visual studio 2012 I created a file by this command :
System.IO.File.Create("config.conf");
after that in the next line I want to use the file by this command :
System.IO.StreamReader rd = new System.IO.StreamReader("config.conf");
But I get This exception :
"The process cannot access the file '\config.far' because it is being used by >another process."
I used thread.sleep(2000) to make application wait but still it doesn't answer.
I will appropriate any help.

File.Create creates the file and returns a FileStream holding the file open.
You can do this:
System.IO.File.Create("config.conf").Dispose();
by disposing of the returned stream object, you close the file.
Or you can do this:
using (var stream = File.Create("config.conf"))
using (var rd = new StreamReader(stream))
{
.... rest of your code here
Additionally, since disposing of the StreamReader will also dispose of the underlying stream, you can reduce this to just:
using (var rd = new StreamReader(File.Create("config.conf")))
{
.... rest of your code here
Final question: Why are you opening a newly created stream for reading? It will contain nothing, so there's nothing to read.

using(var conf = System.IO.File.Create("config.conf"))
{
using (var rd = new System.IO.StreamReader(conf))
{
// Do whatever you want to do with the file here
}
}

The problem is that File.Create returns a stream to the file. That is: The file is already opened for you!
You could do this:
using (System.IO.StreamReader rd = new System.IO.StreamReader(System.IO.File.Create("config.conf")))
{
...
}
By the way, this does not really make sense. What do you expect an empty, newly created file to contain?

When working with files, it is always a good idea to dispose of the file once you are done.
This can be done by two different techniques, the most popular one is using a "using" statement:
using (FileStream fileStream = File.Create(fileNamePath))
{
// insert logic here, for example:
fileStream.SetLength(fileSize);
}
The other one, is calling the .Dispose method.

Close the file if it is opened in notepad or something similar.

Related

Code Stucks at Microsoft.SharePoint.Client.File.OpenBinaryDirect Method

I am trying to download a file using ServeRelativeUrl by OpenBinaryDirect Method and it works fine. But often, irrespective of size, extension or any other file metadata it just get stucks.
Please see the code below, it gets stucks at either of the bolded lines (more often at ExecuteQuery()) and throws an operation timeout error, later I tried to give timeouts (shown in italic) but then it got stuck for infinite time until the main thread got killed.
clientContext.RequestTimeout = -1;
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
clientContext.ExecuteQuery();
using (var fileStream = new FileStream(location, FileMode.Create))
{
fileInfo.Stream.WriteTimeout = -1;
fileInfo.Stream.CopyTo(fileStream);
}
fileInfo.Stream.Dispose();
size of the file in explorer remains 0kb.
Can anyone please help me out with this?
https://i.stack.imgur.com/bKWau.png
I maybe had a similar problem: I got a timeout problem after downloading a lot of files, I solved this by disposing the "fileInfo" object by putting it into a using statement:
using (var fileInfo = File.OpenBinaryDirect(_context, relativeUrl))
{
if (Directory.Exists(targetDirectory))
{
targetDirectory = Path.Combine(targetDirectory,
Path.GetFileName(new Uri(relativeUrl).LocalPath));
}
using (Stream destination = System.IO.File.Create(targetDirectory))
{
for (var a = fileInfo.Stream.ReadByte(); a != -1; a = fileInfo.Stream.ReadByte())
destination.WriteByte((byte)a);
}
}
After that it worked. It seems if the object is not disposed you run into a connection limit.
I just migrated ~100 files from OnPrem to SPO using the same method.
Some difference from my solution:
clientContext.ExecuteQuery();
is only required to ensure file.ServerRelativeUrl is initialized, so you can remove it from this position and load it before.
As I had to download+upload multiple dependend files, I copied each SP binary stream into MemoryStreams with Async methods and disposed the SP streams as fast as possible. I think there will be a connection limit.
I disposed the fileInfo itself instead of the inner Stream object.

Difference Between StreamReader(string filepath) and StreamReader(Stream _stream)

I am little confused between two different constructor of StreamReader class i.e
1.StreamReader(Stream)
I know it takes stream bytes as input but the respective output is same.
here is my code using StreamReader(Stream) contructor
string filepath=#"C:\Users\Suchit\Desktop\p022_names.txt";
using(FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read))
{
using(StreamReader sw = new StreamReader(fs))
{
while(!sw.EndOfStream)
{
Console.WriteLine(sw.ReadLine());
}
}
}
2. StreamReader(String)
This conrtuctor takes the physical file path,
where our respective file exists but the output is again same.
Here is my code using StreamReader(String)
string filepath=#"C:\Users\Suchit\Desktop\p022_names.txt";
using (StreamReader sw = new StreamReader(filePath))
{
while(!sw.EndOfStream)
{
Console.WriteLine(sw.ReadLine());
}
}
So, Which one is better? When and where we should use respective code,
so that our code become more optimized and readable?
A class StreamReader (as well as StreamWriter) is just a wrapper for
FileStream, It needs a FileStream to read/write something to file.
So basically you have two options (ctor overloads) :
Create FileStream explicitly by yourself and wrap SR around it
Let the SR create FileStream for you
Consider this scenario :
using (FileStream fs = File.Open(#"C:\Temp\1.pb", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamReader reader = new StreamReader(fs))
{
// ... read something
reader.ReadLine();
using (StreamWriter writer = new StreamWriter(fs))
{
// ... write something
writer.WriteLine("hello");
}
}
}
Both reader and writer works with the same filestream. Now if we change it to :
using (StreamReader reader = new StreamReader(#"C:\Temp\1.pb"))
{
// ... read something
reader.ReadLine();
using (StreamWriter writer = new StreamWriter(#"C:\Temp\1.pb"))
{
// ... write something
writer.WriteLine("hello");
}
}
System.IOException is thrown "The process cannot access the file C:\Temp\1.pb because it is being used by another process... This is because we try to open file with FileStream2 while we still use it in FileStream1. So generally speaking if you want to open file, perform one r/w operation and close it you're ok with StreamReader(string) overload. In case you would like to use the same FileStream for multiple operations or if by any other reason you'd like to have more control over Filestream then you should instantiate it first and pass to StreamReader(fs) .
Which one is better?
None. Both are same. As the name suggests StreamReader is used to work with streams; When you create an instance of StreamReader with "path", it will create the FileStream internally.
When and where we should use respective code
When you have the Stream upfront, use the overload which takes a Stream otherwise "path".
One advantage of using Stream overload is you can configure the FileStream as you want. For example if you're going to work with asynchronous methods, you need to open the file with asynchronous mode. If you don't then operation will not be truly asynchronous.
When at doubt don't hesitate to check the source yourself.
Note that the Stream overload doesn't take a FileStream. This allows you to read data from any sub class of Stream, which allows you to do things like read the result of a web request, read unzipped data, or read decrypted data.
Use the string path overload if you only want to read from a file and you don't need to use the FileStream for anything else. It just saves you from writing a line of code:
using (var stream = File.OpenRead(path))
using (var reader = new StreamReader(stream))
{
...
}
File.OpenText also does the same thing.
Both are same, just overloads, use one of them according to your need. If you have a local file then you can use StreamReader(string path) otherwise if you have just stream from online or some other source then other overload helps you i-e StreamReader(Stream stream)
Well after searching the new open source reference. You can see that the latter internaly expands to the former one. So passing a raw file path into the StreamReader makes him expand it internaly to a FileStream. For me this means, both are equivalent and you can use them as you prefer it.
My personal opinion is to use the latter one, because its less code to write and its more explicit. I don't like the way java is doing it with there thousand bytereader, streamreader, outputreaderreader and so on...
Basically both works same that is doing UTF8Encodeing and use Buffer of 1024 bytes.
But The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called.
You can refer the following Stream and String
You can use either of them depending on what you have in hand Stream or String file path.
Hope this makes it clear
StreamReader(string) is just an overload of StreamReader(Stream).
In the context of your question, you are probably better off using the StreamReader(string) overload, just because it means less code. StreamReader(Stream) might be minutely faster but you have to create a FileStream using the string you could have just put straight into the StreamReader, so whatever benefit you gained is lost.
Basically, StreamReader(string) is for files with static or easily mapped paths (as appears to be the case for you), while StreamReader(Stream) could be thought of as a fallback in case you have access to a file programmatically, but it's path is difficult to pin down.

Is it necessary to close a file after calling ReadAllText?

I am doing the following:
if (File.Exists(filePath))
{
string base64 = File.ReadAllText(filePath);
return new ImageContentDTO
{
ImageContentGuid = imageContentGuid,
Base64Data = base64
};
}
This works perfectly fine. What I want to ask is if I need to Close the file or anything similar after I am done reading from it. And if so, how?
No, you don't have to explicitly close the file, File.ReadAllText takes care of that for you.
The documentation contains this information very explicitly:
This method opens a file, reads each line of the file, and then adds each line as an element of a string. It then closes the file.
[...]
The file handle is guaranteed to be closed by this method, even if exceptions are raised.
You don't need to close anything when using File.ReadAllText since the underling stream reader is closed implicitely.
MSDN: File.ReadAllText
Opens a text file, reads all lines of the file, and then closes the
file.
Here's the implementation in .NET 4 (ILSpy):
string result;
using (StreamReader streamReader = new StreamReader(path, encoding))
{
result = streamReader.ReadToEnd();
}
return result;
The using statement disposes the StreamReader (even on error), that also closes it.
I know this question has been answered and this is almost a year now but for those who search and read this question, I would like to suggest you close a file when done with it, or at least do an investigation like my answer shows.
I am no programming expert but I have come across this situation recently.
I created a WinForms c# program and used File.ReadAllText to copy text to a string. Afterwards I tried to delete the file, directly from the folder not through the program, but I got an error that the file was still open in another program. I then stopped running the program and was able to delete the file.
That's my experience in Visual Studio 2012 Ultimate. It might be supposed to do something different, but that's what it did for me.
When I used StreamReader.ReadToEnd then StreamReader.Close on the same file, I had no problem deleting the file while running the program.
You have to close IDisposable instances only, usually by means of using, e.g.:
// StreamReader is IDisposable and should be Closed/Disposed
// either explicitly or by using
using (StreamReader sr = new StreamReader(filePath)) {
String base64 = sr.ReadToEnd();
...
}
since you don't have an IDisposable instance in your code (File.ReadAllText
returns String which is not IDisposable) you have nothing to Close/Dispose
StreamWriter outputFile = new StreamWriter(#"C:\Users\Marc\Desktop\_App\files\Data" + dat1 + ".txt");
outputFile.WriteLine(sb.ToString());
outputFile.Close();
StreamWriter outputFileex = new StreamWriter(#"C:\Users\Marc\Desktop\_App\files\DataEx" + dat1 + ".txt");
outputFileex.WriteLine(sbex.ToString());
outputFileex.Close();
Here's a working example I just did with a stringbuilder: "sb". If I remove one of those closes' the file gets generated but the file shows up blank with no data. I had to add in a close to get it to work properly.

Using C# File class to edit file, but throwing exception

I am using the File class to edit an HTML file. I need to delete a line of code from it. The way I am doing it is:
if (selectedFileType.Equals("html"))
{
string contentsOfHtml = File.ReadAllText(paramExportFilePath);
//delete part that I don't want
string deletedElement = "string I need to delete";
contentsOfHtml.Replace(deletedElement, "");
File.WriteAllText(paramExportFilePath, contentsOfHtml);
}
However it is throwing the exception: The process cannot access the file 'path\to\file.html' because it is being used by another process.
I am worried that this is happening because either the File.ReadAllText or File.WriteAllText methods are running on the file, even though in the documentation it specifies that they do close the file. So does anyone know what could be causing this?
If this is a file on a live site then there's a good chance that the web server has a lock on it.
Assuming your working in Windows, try using Process Explorer to see what has a lock on the file.
Whenever you are dealing with Stream based objects, you are always better off wrapping in using statements:
String s1;
using (StreamReader r = new StreamReader(paramExportFilePath, Encoding.ASCII))
{
s1 = r.ReadToEnd();
}
String s2 = s1.Replace("string to delete", "replacement string");
using (StreamWriter w = new StreamWriter(paramExportFilePath, false, Encoding.ASCII))
{
w.Write(s2);
}
The using statements ensure that objects are properly closed and, more importantly, disposed.
Note: replace Encoding.ASCII with whatever you like (perhaps UTF8 if it's HTML code).

Debug file used by another process

Using Visual Studio 2010 and im getting "File is used by another process" almost randomly when trying to read a file. Im reading about 10 xml files into memory with the same procedure
The code that breaks is
private static TextReader CreateTextReader(IsolatedStorageFile isolatedStorageFolder, string path)
{
TextReader textReader = null;
if (isolatedStorageFolder == null)
textReader = new StreamReader(path);
else
textReader = new StreamReader(new IsolatedStorageFileStream(path, FileMode.Open, isolatedStorageFolder));
return textReader;
}
The code breaks 10 percent of the time on
textReader = new StreamReader(path);
I personally think its some kind of garbage collection problem, anyone has any tips on how to debug this kind of problem.
Be sure to call .Dispose or .Close on all steam reader operations that could lock the file. That might be your problem as that code works for me as a flat program.
You need to dispose of the TextReader. Use the using statement like
using (TextReader r = CreateTextReader(...))
{
}
Otherwise the file will remain open when you close your application.
EDIT
You're saying in your comments to the question that you're actually already using using - could it be that the file you're trying to read is actually opened by another application? Sometimes antivir solutions lock files while scanning them or stuff like that - will it work after a short while or do you have to reboot or something like that?

Categories

Resources