In the following code I get the error "stream was not writable":
class Class1
{
private static void Main()
{
FileStream fs = new FileStream("C:\\fFile.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
StreamReader r = new StreamReader(fs);
string t = r.ReadLine();
r.Close();
Console.WriteLine(t);
StreamWriter w = new StreamWriter(fs);
w.WriteLine("string");
w.Flush();
w.Close();
fs.Close();
}
}
The error occurs at this line StreamWriter w = new StreamWriter(fs);
Why is this?
from msdn
Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
So the stream you try to write to is invalid you need to reopen the stream and reopen the file.
r.Close();
There's your problem after you read. The close() methods close the underlying stream.
You'll have to re-open the file since the read closes it:
FileStream fs = new FileStream("C:\\test.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
using (StreamReader r = new StreamReader(fs))
{
string t = r.ReadLine();
r.Close();
Console.WriteLine(t);
}
fs = new FileStream("C:\\test.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine("string");
w.Flush();
w.Close();
}
fs.Close();
Dont close the first StreamWriter, it will close the underlying stream.
And use using statements as Oscar suggests.
using (FileStream fs = new FileStream("C:\\temp\\fFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
StreamReader r = new StreamReader(fs);
string t = r.ReadLine();
Console.WriteLine(t);
StreamWriter w = new StreamWriter(fs);
w.WriteLine("string");
w.Close();
r.Close();
fs.Close();
}
Do not close the StreamReader. Just comment the line below and it will work.
r.Close();
Related
I have the following problem:
I use this code to open a file and write to it:
using (FileStream fileStream = new FileStream(saveDir + #"\" + saveFile, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write("Test");
streamWriter.Close();
}
but in the "using" line it tells me that it can not open the file because it is used by another process but the file is not open and isn't used. What's wrong?
I searched around this forum and the internet but I can't find a solution.
You could try using FileMode.OpenOrCreate instead of creating the file "manually":
using (FileStream fileStream = new FileStream(saveDir + #"\" + saveFile,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.Write("Test");
streamWriter.Close();
}
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
}
I have 2 applications, one is writing to a file, and the other one reads the file. It's a log file, so the writer will be logging until the program stops, while the reader could be invoked any time to get the content of the file.
I thought that when the writer opens the file with FileShare.Read, the reader would be able to access the file, but it produces an error saying that the file is being used by another process.
Writer Application:
FileStream fs = new FileStream("file.log", FileMode.Open, FileAccess.Write, FileShare.Read);
BinaryWriter writer = new BinaryWriter(fs);
Reader Application:
BinaryReader reader = new BinaryReader(File.OpenRead("file.log"));
How do I prevent this error?
Can you try specifying FileShare.Read while reading the file also? Instead of directly using File.OpenRead use FileStream with this permission.
Also, for logging, you can use log4Net or any other free logging framework which manages logging so efficiently and we do not have to manage writing to files.
o read a locked file you are going to need to provide more flags for the FileStream.
Code such as below.
using (var reader = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Read,FileShare.ReadWrite))
{
using (var binary = new BinaryReader(reader))
{
//todo: add your code
binary.Close();
}
reader.Close();
}
This would open the file for reading only with the share mode of read write. This can be tested with a small app. (Using streamreader\write instead of binary)
static Thread writer,
reader;
static bool abort = false;
static void Main(string[] args)
{
var fs = File.Create("D:\\test.txt");
fs.Dispose();
writer = new Thread(new ThreadStart(testWriteLoop));
reader = new Thread(new ThreadStart(testReadLoop));
writer.Start();
reader.Start();
Console.ReadKey();
abort = true;
}
static void testWriteLoop()
{
using (FileStream fs = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Write, FileShare.Read))
{
using (var writer = new StreamWriter(fs))
{
while (!abort)
{
writer.WriteLine(DateTime.Now.ToString());
writer.Flush();
Thread.Sleep(1000);
}
}
}
}
static void testReadLoop()
{
while (!abort)
{
Thread.Sleep(1000);
using (var reader = new FileStream("d:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var stream = new StreamReader(reader))
{
Console.WriteLine(stream.ReadToEnd());
stream.Close();
}
reader.Close();
}
}
}
I realize the example above is pretty simple but the fact still remains that the "testWriteLoop" never releases the lock.
Hope this helps
This function doesn't work because another process is using it.
The function must read the file, do something with it's data and write the result to this file.
private void changeToolStripMenuItem_Click(object sender, EventArgs e)
{
LB2.Visible = true;
TB2.Visible = true;
SaveFileDialog save = new SaveFileDialog();
if (save.ShowDialog() == DialogResult.OK)
{
double maxlen;
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Find(read, out maxlen);
while (read.BaseStream.Position < read.BaseStream.Length)
{
double A = read.ReadDouble();
if (A > 0)
{
read.BaseStream.Seek(-8, SeekOrigin.Current);
w.Write(Find(read, out maxlen));
}
else
w.Write(A);
}
read.BaseStream.Close();
w.BaseStream.Close();
}
}
my psychic debugging sense says that it's the FILE that's in use
And you're getting the error because you didn't close your BinaryReader before you created your BinaryWriter
instead of this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
read.BaseStream.Close();
w.BaseStream.Close();
do this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
...
read.BaseStream.Close();
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
w.BaseStream.Close();
you seem to be opening the same file twice?
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Same file. BinaryWriter probably encounters the exception, though I'm not entirely sure because you haven't showed us. You need to close your BinaryReader before you can do anything else with that file.
I would do this to make sure your streams are getting closed
using( BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open)))
{
using( BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create)) )
{
// CODE HERE
}
}
It sounds like you're getting an exception and you're not closing your streams/readers/writers.
Change it to:
var fs=new FileStream(save.FileName, FileMode.OpenOrCreate);
BinaryReader read=new BinaryReader(fs);
BinaryWriter w=new BinaryWriter(fs);
and remove:
w.BaseStream.Close();
In the following, streamwriter is not throwing an exception if the file does not exist.
I expected it to raise an exception, why doesn't it and how can I get it to do so?
var fileName = HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/emails.txt");
FileStream fs = new FileStream(fileName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(String.Format("{0}\t{1}", email, name));
sw.Flush();
sw.Close();
fs.Close();
Why?
FileStream fs = new FileStream(fileName, FileMode.Append);
This will create the file if it doesn't exist (and append to it if it does).
Assuming from your post (there is no question in it!) you don't want it to create a file first call File.Exists to ensure the file exists.
If you want to make sure you're appending to an existing file, use FileMode.Open and then Seek to the end before writing.
With File.Exists there is a (very slim) chance of an other process deleting the file after checking but before the construction of the FileStream.
Try this:
try
{
var fileName = HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/emails.txt");
if (System.IO.File.Exists(fileName ))
{
FileStream fs = new FileStream(fileName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(String.Format("{0}\t{1}", email, name));
sw.Flush();
sw.Close();
fs.Close();
}
else
{
//Throw error here
}
}
catch()
{
}