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..
Related
I want to read a binary file line by line (I'm writing of course continously, but I know that after 457 bytes new data start and I know exactly the byte structure and where which information is written to) and change a special entry of the line. I get an System.IO.IOException when I try to access the same file with both BinaryReader and BinaryWriter. I use locking to prevent that the file is accessed from somewhere else.
My code is:
using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs2))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write), utf8))
{
for (int i = 0; i < 11000; i+=457)
{
int myint = r.ReadInt64();
bw.Seek(i, SeekOrigin.Current);
bw.Write(myint*2);
}
}
}
}
How can I do this?
Do not create the second FileStream because the file is locked for the read operation by the first FileStream object.
If you are sure about file structure, the exception only can come out from 2nd FileStream instantiation. See link below for more information:
Read and Write to File at the same time
It is working for me using the following code:
if (File.Exists(testfile))
{
FileInfo fi = new FileInfo(testfile);
using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BinaryReader r = new BinaryReader(fs2))
{
r.BaseStream.Seek(0, SeekOrigin.Begin);
using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)))
{
for (int i = 0; i <= (fi.Length-177); i += 177)//181
{
}
}
}
}
}
I encrypted a pdf and would like to save it to the database, below are the codes as to how I did it. I would like to know if there are any ways to set the Created "PDFEncrypted.pdf" onto the Stream fs without using a FileUploader?
string WorkingFolder = Server.MapPath("~/Files/");
string InputFile = Path.Combine(WorkingFolder, "PDF.pdf");
string OutputFile = Path.Combine(WorkingFolder, "PDFEncrypted.pdf");
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(InputFile);
PdfEncryptor.Encrypt(reader, output, true, "pass123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
So I have these codes to upload it
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
I want to read data from exe file.
On java i read exe perfect from start to end,
bun on c# i cannot read all file.
File lenth is true but in result show only head of exe file
string fileLoc = filePaths[0];
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach(byte b in bin){
Console.Write((char)b);
}
fs.Close();
output is only the head of exe: MZP
Cannot reproduce:
string fileLoc = //my path to git.exe
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
fs.Close()
It writes all data from it.
But i see many problems in your code:
1) never do work with files with such unsafer way (if error occured file will not close) rewrite:
string fileLoc = //my path to git.exe
using(FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
} // no more explicit close required, but it will closed with guarantee
2) not mistake but in C# it's preferable use var (analoug to auto in c++)
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var br = new BinaryReader(fs);
var bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (var b in bin)
{
Console.Write((char)b);
}
} //it still strong typed, but type referenced only once at right side of assigment
3) Not require use Convert for explicitly castable types (long->int)
var bin = br.ReadBytes((int)fs.Length);
4) I don't know why only MZP is written in your case, but can imagine that if you cast byte to char you will get many not-printable symbols including \r \n \f and so on in output - how your concrete terminal will be react? - i don't know
5) If you print (char)b just for test of bin - why so badly - why you not simply test bin.Length or why you print (char)b and not b+" " ? Otherwise if you really want to print bytes to console - it's bad idea anyway - look (4)
6) Why BinaryReader? if you just want read all
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var bin = new byte[(int)fs.Length];
// u can use usual stream pattern
int l=0; while((l+=fs.Read(bin,t,bin.Length-t))<bin.Length);
foreach (var b in bin)
{
Console.Write((char)b);
}
}
/*Initialize FileStreams for both writing and reading*/
writeStream = new FileStream(logfilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
readStream = new FileStream(logfilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
/*Initialize the Writer and Reader*/
fileWrite = new StreamWriter(writeStream);
fileRead = new StreamReader(readStream);
So this is what I use to be able to constantly write and read to the same file. How can I clear the file without the need to close both streams temporarily, clear file, and reopen them again?
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));