FileStream string method for Read/Write? - c#

I am absolute beginner and I am using VS Community 2017 C# and trying to open file on my android phone (7.0 API 24) and write and read some text in that file. This is my methods that suppose to do that:
public string WriteFile(string fileName, byte content)
{
FileStream fileStream = new FileStream(#fileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
fileStream.WriteByte(content);
fileStream.Close();
return "WriteOpen";
}
public string ReadFile(string fileName)
{
FileStream fileStream = new FileStream(#fileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
int tekts = fileStream.ReadByte();
fileStream.Close();
return "" + tekts;
}
but I cannot find FileStream method with string arguments, so I use WriteByte and ReadByte just to test writing and reading file.
Any suggestions?

Related

How create instance FileStream from FileStream?

How create new instance FileStream without specifying other parameters in the constructor, instead of parameters from source FileStream. How can I do it?
FileStream fs= new FileStream([any parametrs]);
FileStream copy1= new FileStream(parametrs from fs); // First variant
FileStream copy2= new FileStream(fs); // Or second variant
For example, I create fileStream
FileStream fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4 * 1024, true)
Now I want a lot of independent copies from it, but fs doesn't save any parametrs received from constructor.
What's about Stream.CopyTo();
FileStream fs= new FileStream([any parametrs]);
var copy1 = new MemoryStream();
fs.CopyTo(copy1)
It should work
Solved like this
class FileStreamExt : FileStream
{
private string _fileName;
private FileMode _mode;
public FileStreamExt Clone()
{
return new FileStreamExt(_fileName, _mode);
}
public FileStreamExt(string filename, FileMode mode)
: base(filename, mode)
{
_fileName = filename;
_mode = mode;
}
}
FileStreamExt fs = FileStreamExt(_fileName,FileAccess.Read);
FileStreamExt copy = fs.Clone();

Read and write to a file in the same stream

I'm trying to read and write to the same file in a way such that no other program can access the file in between:
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);
newString = sr.ReadToEnd() + "somethingNew";
sw.Write(newString);
fs.Close();
The file is never written to. If I debug I can see that the reader manages to fetch the contents of the file, but the writer does not seem to be able to write to the file. Nothing happens.
I've been looking at this question which seems to be the same as mine. However I'm not able to get it to work.
Just Flush your changes to file, Have sw.Flush(); before closing the stream. like:
string filePath = "test.txt";
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);
newString = sr.ReadToEnd() + "somethingNew";
sw.Write(newString);
sw.Flush(); //HERE
fs.Close();
You may see this post simultaneous read-write a file in C# (open multiple streams for reading and writing)
As mentioned above - just add the Flush() to force the data held in the stream to be written to the file. In a comment you mentioned that you had previously used a 'using' statement but this hadn't worked.
Briefly here's why:
A using statement automatically calls Flush() so you don't have
to.
When you dispose of a StreamReader (or StreamWriter) - like by using a 'using' statement - the inner stream object is also disposed and you lose the handle to the stream.
#EJS a simple static method that you can use to create a new file if it does not exist as well as write to the same file if it does exist
Simple usage
string path = #"C:\SomePath\Name.txt";
if (!System.IO.File.Exists(path))
{
WriteAndOrAppendText(path, "File Created");
}
else if (System.IO.File.Exists(path))
{
WriteAndOrAppendText(path, "New Boot.");
}
private static void WriteAndOrAppendText(string path, string strText)
{
if (!File.Exists(path))
{
using (StreamWriter fileStream = new StreamWriter(path, true))
{
fileStream.WriteLine(strText);
fileStream.Flush();
fileStream.Close();
}
}
else
{
using (StreamWriter fileStream2 = new StreamWriter(path, true))
{
fileStream2.WriteLine(strText);
fileStream2.Flush();
fileStream2.Close();
}
}
}
For being able to create a file, append to it, and read the data in it while still allowing an application to write to it, as I believe you are trying to do, here's a set up I created:
string path = #"C:\SomePath\MyLogFile.txt";
public static string Log(string Message)
{
try
{
if (File.Exists(path) == false)
File.Create(path).Close(); // need this .Close()!!!
logCounter++;
string logString = logCounter + " " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Message + Environment.NewLine;
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(logString);
}
}
return logString; // only necessary so we can return an error in the Exception block
}
catch (Exception ex)
{
return "Logger: Cannot log data. " + ex.ToString();
}
}
It's actually required to use FileAccess.Write if you do FileMode.Append - instead of being able to use FileAccess.ReadWrite - but I found that didn't matter because whatever had been written would have been closed and flushed to the file, and I could still open the file and read it (it wouldn't be locked & blank) using these. I have sw.Write() because I have Environment.NewLine that I added into my logString, but I could've done sw.WriteLine() and removed that, if I had wanted to.
One caveat: File.Exists() has issues if the path is long - can't remember the limit, but just know that there is one, so don't put your file you're writing to several layers deep. Less is always better.

StreamWriter cannot write into a file although it is closed

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();
}

C# FileStream behavior End of file

There is a behavior of C# Filestream I don't get. I have a file. This file contains a string with a length of three. When I open a file stream and overwrite it with an string with a length of six chars, it contains the new string but only the first three chars. It is truncated to the previous length.
using (FileStream fs = File.open(rootPath + filePath, FileMode.Truncate, FileAccess.Write, FileShare.None))
{
bool write = fs.CanWrite;
bool canSeek = fs.CanSeek;
byte[] data = Encoding.ASCII.GetBytes(sixchars);
fs.Write(data, 0, data.Length);
fs.Flush();
}
So why is this so and how can I work around?
I tried it with FileMode.Create too. CanWrite and CanSeek are true;
EDIT
Ok here an Code Sample that compiles. I created the file in windows explorer and wrote "123" into it before.
string path = #"C:\1\test.txt";
using (FileStream fs = File.Open(path , FileMode.Truncate, FileAccess.Write, FileShare.None))
{
byte[] data = Encoding.ASCII.GetBytes("666666");
fs.Write(data, 0, data.Length);
fs.Flush();
}
I also tried
File.WriteAllText(path , "666666");
and
byte[] datas = Encoding.ASCII.GetBytes("666666");
File.WriteAllBytes(path , datas);
After all the result is still 666 instead of 666666.
Try to use
File.WriteAllText(Path.Combine(rootPath, filePath), sixchars, Encoding.ASCII);
of
File.WriteAllBytes(Path.Combine(rootPath, filePath), Encoding.ASCII.GetBytes(sixchars));

How to Overwrite Existing Text Using FileStream

NOTE: I can't use FileMode.Create or FileMode.Truncate because they would cause some unwanted problem
byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
FileStream f = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
f.Write(data, 0, data.Length);
f.Close();
This will append new text to the top of the old one. How can I overwrite everything?
your code
byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
FileStream f = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
f.Write(data, 0, data.Length);
f.Close();
how come you can't do something like this..? please explain why you can't use FileMode.Create
byte[] data = new UTF8Encoding().GetBytes(this.Box.Text);
using(Stream f = File.Open(path, FileMode.Write))
{
f.Write(data, 0, data.Length);
}
you could also do something like the following
1. Let the users write to the same file
2. capture the users Machine Name or User Id then
2. write a line in your file like this
strSeprate = new string('*',25);
//will write to the file "*************************";
f.Write(strSeprate);
f.Write(Machine Name or UserId);
f.Write(data);
f.Write(DateTime.Now.ToString());
f.Write(strSeprate);
just an idea..

Categories

Resources