Cannot accessed to a file that was opened and closed - c#

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
}

Related

C# File.ReadAllText The process cannot access the file because it is being used by another process

after editing the xml content, my code keeps saying "The process cannot access the file 'path' because it is being used by another process." gets the error. Waiting for your solutions.
var regex = new Regex(#"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.Compiled);
var memStream = new MemoryStream();
using (Stream sr = File.Open(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
sr.CopyTo(memStream);
sr.Close();
sr.Dispose();
}
using (Stream sr = File.Open(file.FullName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
var text = Encoding.ASCII.GetString(memStream.ToArray());
var result = regex.Replace(text, String.Empty);
byte[] bArray = Encoding.UTF8.GetBytes(result);
sr.Write(bArray, 0, bArray.Length);
sr.Close();
sr.Dispose();
memStream.Close();
memStream.Dispose();
}
string xml = File.ReadAllText(xmlFile.FullName);
(Adding here as would be a mess a comment)
If this worked, wouldn't it leave garbage at the end of XML file and make it invalid? Why not simply ReadAllText, replace and WriteAllText. ie:
var regex = new Regex(#"[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.Compiled);
string xml = regex.Replace(File.ReadAllText(file.FullName), String.Empty);
File.WriteAllText(file.FullName, xml);

Using memory stream instead of filestream for AWS C# S3 SDK not returning full file

I have some code that is meant to retrieve a file from an S3 bucket and deserialize the file. When I use a file stream I get all the data no problem, but when I use a memory stream it seems like I am not getting all of the data:
It doesnt get the full XML:
Where it should look like:
Here is the code I am using:
internal object ReadDataContractFromFile(string filename, Type type)
{
GetObjectRequest getObjRequest = new GetObjectRequest();
MemoryStream memoryStream = new MemoryStream();
getObjRequest.BucketName = bucketName;
getObjRequest.Key = filename;
string path = #"C:\{PATH_TO_FILE}\requests\" + filename;
FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
using (GetObjectResponse getObjRespone = s3Client.GetObject(getObjRequest))
using (Stream responseStream = getObjRespone.ResponseStream)
{
responseStream.CopyTo(fileStream);
//memoryStream.Seek(0, 0);
XmlReaderSettings rs = new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Fragment,
};
XmlReader r = XmlReader.Create(fileStream, rs);
return new DataContractSerializer(type).ReadObject(r);
}
}
If I use memoryStream in place of the fileStream variable, I get the incomplete XML I showed above. I tried to seek to the beginning of the stream incase the position was wrong but that didnt fix it. Any idea what Im doing wrong?

Why i get URI formats are not supported in c#?

I'm new in c#,and write this code:
const string file ="http://ipaddress/"+"1.jpg";
var fileName = file.Split('\\').Last();
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
var fts = new FileToSend(fileName, fileStream);
await Bot.SendPhotoAsync(update.Message.Chat.Id, fts, "Nice Picture");
}
but in this line:
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
get this error:
URI formats are not supported
How can i solve that problem ?thanks.
I'd suggest you use WebClient instead of FileStream for this. Here's a link that might help you: URL Formats are not supported
Hope it helps!

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

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

File sharing for a separate writer and reader application in C#

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

Categories

Resources