The process cannot access the file because it is being used by another process - c#

public bool ReadFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string res = sr.ReadToEnd();
if (res == "1")
return true;
else
return false;
}
public void WriteToFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.Open,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write("1");
}
So it should work like if ReadFile returns false than i do WriteFile.
But when it reaches writefile, it throws IO expection:
The process cannot access the file ... because it is being used by another process

You aren't closing the file when you read it.
Put your FileStream and StreamReader objects in using statements:
using (var fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read)) {
using (var sr = new StreamReader(fs)) {
//read file here
}
}
Make sure you do the same when you write to the file.

You need to dispose the StreamReader object in the ReadFile method. The StreamReader inherits from IDisposable and therfor you need to dispose the object.
Check this link for more info:StreamReader Class

Related

C# StreamWriter won't work after calling StreamReader

I'm trying to make betting program in C#, storing the user's data in a txt file. I have no problem reading the data from it. However, I can't manage to overwrite it.
From what I've tested, if I call the StreamWriter part alone the overwriting happens just fine. When I put the same code after the StreamReader part, the code will reach the Console.WriteLine("reached"); line and ignore everything after it (username is never written in the console). No error is detected and compilation won't stop either.
Here's the class code:
class Dinero
{
private List<string> data;
private string path = #"C:\Users\yy\Documents\Visual Studio 2015\Projects\ErikaBot\ErikaBot\img\bank_data.txt";
...
some other methods here
...
public void thing(string username, int money)
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
data = new List<string>();
using (StreamReader sr = new StreamReader(fs))
{
string a = sr.ReadLine();
for (int i = 0; a != null; i++)
{
if (a != username)
{
data.Add(a);
}
else i++;
a = sr.ReadLine();
}
}
string b = Convert.ToString(money);
Console.WriteLine("reached");
using (StreamWriter tw = new StreamWriter(fs))
{
Console.WriteLine(username);
if (data != null)
{
for (int i = 0; i < data.Count; i++)
{
tw.WriteLine(data.ElementAt(i));
}
}
string money2 = Convert.ToString(money);
tw.WriteLine(username);
tw.WriteLine(money2);
}
}
}
By disposing StreamReader you also dispose the FileStream.
Either repeat the filestream initialisation before the using statement for StreamWriter or put the latter in the using statement for StreamReader.

Cannot accessed to a file that was opened and closed

through my application, i open a text file, read it and than close it.
then, manually accessing to that file is restricted.
how do i solve it?
here is my code:
fs = new FileStream(#"C:\Weather\somePlace.json", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader streamReader = new StreamReader(fs))
{
String responseData = streamReader.ReadToEnd();
//Deserialize the json output
var outObject = JsonConvert.DeserializeObject<RootObject>(responseData);
// do something with the information
fs.Close();
fs = null;
}
thanks !
You don't need the FileStream actually. You can just use this:
using (StreamReader streamReader = new StreamReader(#"C:\Weather\somePlace.json"))
{
String responseData = streamReader.ReadToEnd();
//Deserialize the json output
var outObject = JsonConvert.DeserializeObject<RootObject>(responseData);
// do something with the information
}
As FileStream is IDisposable, it should be disposed after usage.
So wrap it into using to ensure file will be released:
using(fs = new FileStream(#"C:\Weather\somePlace.json", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
// the rest of your code
}

c# exception file is being used by another process

i have trouble with the following two functions. Both have a indentical basic scheme but first one work, second one causes an exception at marked line("File is used by another process").
// this works
public static void EncryptFile(string FileName)
{
string ToEncrypt = null;
using(StreamReader sr = new StreamReader(FileName))
{
ToEncrypt = sr.ReadToEnd();
}
using(StreamWriter sw = new StreamWriter(FileName, false))
{
string Encrypted = Encrypt(ToEncrypt, true);
sw.Write(Encrypted);
}
}
// this works not - see commented lin
public static void DecryptFile(string FileName)
{
string ToDecrypt = null;
using (StreamReader sr = new StreamReader(FileName))
{
ToDecrypt = sr.ReadToEnd();
}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
I have tried with an additional Close() after read and write, but this works not too.
I hope, somebody can help.
Thanks
Torsten
Is the function called from multiple threads? If yes you may want to declare a static object on class level and place a lock statement around the entire body of that method. Like this:
private static Object syncObject = new Object()
// this works not - see commented lin
public static void DecryptFile(string FileName)
{
lock(syncObject)
{
string ToDecrypt = null;
using (StreamReader sr = new StreamReader(FileName))
{
ToDecrypt = sr.ReadToEnd();
}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
}
Also could you, just for fun, comment the StreamReader statement and try to run the method again? If it still doesn't work, check if you've that file open in a texteditor or something alike by using ProcessExplorer or something similiar.
edit
could you comment the StreamReader part? So that it looks like this:
public static void DecryptFile(string FileName)
{
//string ToDecrypt = null;
//using (StreamReader sr = new StreamReader(FileName))
//{
// ToDecrypt = sr.ReadToEnd();
//}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
also could you try to open an exclusive FileStream on that file before the StreamReader and once after the StreamReader but before the StreamWriter? http://msdn.microsoft.com/de-de/library/tyhc0kft%28v=vs.110%29.aspx
Also could you try and use another file for that method?

Append throwing an exception

I was trying to create a fixed lenght(left aligned) batch file with the below code.
when i use Append it's throwing exception "is a method but used like a type".
string batFilePath = #"c:\mockforbat.bat";
if (!File.Exists(batFilePath))
{
using (FileStream fs = File.Create(batFilePath))
{
fs.Close();
}
}
//write
using (StreamWriter sw = new File.AppendText(batFilePath))
{
string a = String.Format("{0,-24}{1,-5}{2,5}", "CostCenter", "CostObject", "ActivityType");
sw.WriteLine(#a);
}
Process process = Process.Start(batFilePath);
process.WaitForExit();
Please some one correct me what i did wrong here ?
Drop the new operator from this line
using (StreamWriter sw = new File.AppendText(batFilePath))
It should read
using (StreamWriter sw = File.AppendText(batFilePath))
string batFilePath = #"c:\mockforbat.bat";
using(var fs = new FileStream(batFilePath , FileMode.OpenOrCreate, FileAccess.Write))
{
using(var sw = new StreamWriter(fs))
{
string a = String.Format("{0,-24}{1,-5}{2,5}", "CostCenter", "CostObject", "ActivityType");
sw.WriteLine(a);
}
}

Dispose an object that is used in the constructer of another object

I am using this code to read values from an isolated storage
IsolatedStorageFile isoStore = null;
StreamReader reader = null;
IsolatedStorageFileStream isolatedStorageFileStream = null;
String strIsolatedStorageValue = string.Empty;
isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
try
{
isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore);
// This code opens the store and reads the string.
reader = new StreamReader(isolatedStorageFileStream);
// Read a line from the file and add it to sb.
strIsolatedStorageValue = reader.ReadLine();
}
catch (Exception)
{
}
finally
{
if (isolatedStorageFileStream != null)
{
isolatedStorageFileStream.Dispose();
}
if (reader != null)
{
reader.Dispose();
}
}
// Return the string.
return strIsolatedStorageValue;
The problem is that when I am disposing isolatedStorageFileStream and then disposing the reader, visual studio tells me that isolatedStorageFileStream could be disposed more than once! and when not disposing it I am getting the warning that isolatedStorageFileStream should be disposed first.
What to do in such a case, that is disposing an object used in the constructor of another disposable object
Thanks
You should dispose the reader before the filestream.
To simplify your code, you should make use of using blocks. They do the try/finally/dispose pattern automagically for you:
using (isolatedStorageFileStream = new IsolatedStorageFileStream(
strKey + ".txt", FileMode.OpenOrCreate, isoStore)) {
// This code opens the store and reads the string.
using (reader = new StreamReader(isolatedStorageFileStream)) {
strIsolatedStorageValue = reader.ReadLine();
}
}
Use the using keyword:
using (IsolatedStorageFileStream isolatedStorageFileStream =
new IsolatedStorageFileStream(
strKey + ".txt", FileMode.OpenOrCreate, isoStore))
using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
{
// Read a line from the file and add it to sb.
strIsolatedStorageValue = reader.ReadLine();
}
return strIsolatedStorageValue;
using safely calls Dispose for you and you don't have to call it manually.
The using statement automatically does try-finally for IDisposable (dispose if not null) for you.
using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(strKey + ".txt", FileMode.OpenOrCreate, isoStore))
{
using (StreamReader reader = new StreamReader(isolatedStorageFileStream))
{
string strIsolatedStorageValue = reader.ReadLine();
return strIsolatedStorageValue;
}
}

Categories

Resources