c# Two FileStreams write to text file but just one affect file - c#

below code:
var fs = new FileStream(#"C:\Users\Michał\Desktop\tools\test.txt",
FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
var fs2 = new FileStream(#"C:\Users\Michał\Desktop\tools\test.txt",
FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
int a = 0;
while (a < 3)
{
byte[] info = new UTF8Encoding(true).GetBytes("DEF_");
byte[] info2 = new UTF8Encoding(true).GetBytes("abc_");
fs.Write(info, 0, info.Length);
Thread.Sleep(100);
fs2.Write(info2, 0, info2.Length);
Thread.Sleep(1000);
++a;
}
fs.Close();
fs2.Close();
Why result is that in a file there is just "abc_abc_abc" ?
FileShare.ReadWrite means for me other processes/threads can write to this file in the same time in FileStream ctor call.

You can achieve the desired behavior as follows:
using (var fs = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
using (var fs2 = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
byte[] info = new UTF8Encoding(true).GetBytes("DEF_");
byte[] info2 = new UTF8Encoding(true).GetBytes("abc_");
for (int i = 0; i < 3; i++)
{
fs.Seek(0, SeekOrigin.End);
fs.Write(info, 0, info.Length);
fs.Flush();
fs2.Seek(0, SeekOrigin.End);
fs2.Write(info2, 0, info2.Length);
fs2.Flush();
}
}
Before writing, each pointer of stream must be positioned at the end. This is done using the Seek method.
After writing, you need to flush the buffer to disk. This ensures that the stream is in the correct state before starting the next write. To do this, use the Flush method.
When you create a stream in its constructor, you can specify the FileOptions.WriteThrough. According to its description, the intermediate buffer should not be used. However, it still doesn't work without the Flush method. Perhaps experts will explain the reason.

Related

In FileStream.ReadAsync we still have to use split logic?

My Current Project download manger tool have code like this(For downloading large files from file share, on shcedule) :
using (var destinationFileStream = new FileStream(sourceFilename, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, buffer.Length, false))
{
while (true)
{
if (file.Read(buffer, 0, buffer.Length) <= 0)
break;
destinationFileStream.Write(buffer, 0, buffer.Length);
....
... Bandwidth throttling Code
....
}
}
}
if i convert this to FileStream.ReadAsync code , still i have to use split file to buffer size logic and download or this is handled internally by .net ?

Failed to use GZipStream to decompress a file (without using CopyToAsync)

I'm trying to to decompress a MemoryStream using ReadAsync/WriteAsync but it's not working.
int bufferSize = 8192;
using (var memoryStream = new MemoryStream())
using (var fileStream = new FileStream(destinationFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
// ... populate the MemoryStream ...
memoryStream.Position = 0;
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress, true))
{
////await gzipStream.CopyToAsync(fileStream);
byte[] buffer = new byte[bufferSize];
while (await gzipStream.ReadAsync(buffer, 0, bufferSize) > 0)
{
await fileStream.WriteAsync(buffer, 0, bufferSize);
}
}
await fileStream.FlushAsync();
}
The gzipStream.CopyToAsync works but not the other way. Why?
Thanks.
ReadAsync is returning number of bytes read - you're ignoring that number. You can only WriteAsync the exact count of bytes you've read first.

C# FileStream read set encoding

There might be something obvious I'm missing here, but I can't seem to set the encoding on my FileStream read. Here's the code:
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
using (fs)
{
byte[] buffer = new byte[chunk];
fs.Seek(chunk, SeekOrigin.Begin);
int bytesRead = fs.Read(buffer, 0, chunk);
while (bytesRead > 0)
{
ProcessChunk(buffer, bytesRead, database, id);
bytesRead = fs.Read(buffer, 0, chunk);
}
}
fs.Close();
Where ProcessChunk saves the read values to objects which are then serialized to XML, but the characters read appear wrong. The encoding needs to be 1250. I haven't seen an option to add the encoding to the FileStream. What am I missing here?
Rather than FileStream, use StreamReader. It has several constructors which allow you to specify the Encoding. For example:
StreamReader sr = new StreamReader(file, System.Text.Encoding.ASCII);
Since you require encoding 1250, this can be done with:
StreamReader sr = new StreamReader(file, System.Text.Encoding.GetEncoding(1250));
I would also suggest writing it as:
using (StreamReader sr = new StreamReader ...etc)
rather than declaring the variable outside the using; and you don't need to do the Close outside the using, since the Dispose will handle that.
You can also use both FileStream and FileReader :
using (FileStream fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding(1252)))
{
while (!sr.EndOfStream)
ProcessLine(sr.ReadLine());
}
}

Error "file in use" when playing aac while appending bytes to aac

var outputfile = "outputfile.aac";
var fileList = new List<string>
{
"1.aac",
"2.aac",
"3.aac",
"4.aac",
"5.aac",
"6.aac"
};
foreach (var file in fileList)
{
using (var stream = new FileStream(outputfile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
var bytes = File.ReadAllBytes(file);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
}
I try to join aac files in fileList into outputfile. when writing file "3.aac" to outputfile.aac, I open outputfile with MediaPlayer, then the FileStream returns exception "file in use", even FileShare mode is ReadWrite, it means that other processes can read and write to the file. So where is the reason?
However, in this case output file is not blocked
Stream s = resp.GetResponseStream();
var fs = File.Exists(outputFile) ? new FileStream(outputFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
: new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
byte[] buffer = new byte[4096];
while (s.CanRead)
{
int bytesRead = s.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
}
P/s: I found that the reason because it's aac file
When you use FileShare.ReadWrite you allow subsequent opening of the file in read or write mode.
MediaPlayer then opens the file with FileShare.Read on its side, denying you write access to the file.

How to access and save embedded resources to the local disk in C#?

I have a set of Folders(in Resources) which contains the Configuration files,I need to save this folder in the User's path.(if they don't have) for this reason only i added the Folders in Resources. Do anyone have any idea on how to save the Files in the Resources.
using (System.IO.FileStream fs = new System.IO.FileStream(pathConfigurationFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
byte[] data = Properties.Resources.YourConfigurationFile;
fs.Write(data, 0, data.Length);
}
var data = Properties.Resources.ResourceName;
using(var stream = new FileStream(file, FileMode.Create))
{
stream.Write(data, 0, data.Count() - 1);
stream.Flush();
}

Categories