I have a problem. When I run my program, it comes up with an error, specifically the CS1023 error. I guess it's because I have a declaration inside a statement, but I don't know how else to write the code. Sometimes C# annoys me, because in C++ I could get away with similar things... anyway, here's the code. I would appreciate it if somebody could explain it to me.
Error Message Link
void BtnTotalSeasonsClick(object sender, EventArgs e)
{
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
{
stream.Position = 4;
Stream.WriteByte(0xCD);
}
}
Fixed Code with CS0120 error.
{
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))
{
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
stream.Position = 4;
Stream.WriteByte(0xCD);
}
}
There's nothing apparently wrong with the code you pasted in. Perhaps the error is somewhere else above this, and the compiler is getting confused?
Ah, I see you've changed the code.
The problem here is you are declaring the Byte[] array outside the intended using block. Since the scope of the declaration as is is only one line, this constitutes a logic error, and the compiler catches it with a compile-time error.
The compiler is interpreting your code like this:
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))
{
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
}
{
stream.Position = 4;
stream.WriteByte(0xCD);
}
To fix it, move the Byte[] inside the braces, or outside the using block:
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))
{
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
stream.Position = 4;
stream.WriteByte(0xCD);
}
-or-
Byte[] bytes = System.Text.ASCIIEncoding.GetBytes(txtTotalSeasons.Text);
using (var stream = new FileStream(drvFile, FileMode.Open, FileAccess.ReadWrite))
{
stream.Position = 4;
stream.WriteByte(0xCD);
}
Personally, I like being annoyed by the compiler here, since it saves me from a run-time error.
Related
When I try to do the following with .zip folder witch contains some videos I get out of memory exeption.
Byte[] bytes = File.ReadAllBytes(#"C:\folderWithVideos.zip");
String base64File= Convert.ToBase64String(bytes);//<----- out of memory exception
How to handle this exception properly? I mean without try-catch, I have tried something like:
String base64File;
if (bytes.Length <= System.Int32.MaxValue)
base64File = Convert.ToBase64String(bytes);
But it didn't helped, but bytes.Length <= 255 did helped, but I'm not sure that 255 is the right number.
Based on the code shown in the blog the following code works.
// using System.Security.Cryptography
private void ConvertLargeFile()
{
//encode
var filein = #"C:\Users\test\Desktop\my.zip";
var fileout = #"C:\Users\test\Desktop\Base64Zip";
using (FileStream fs = File.Open(fileout, FileMode.Create))
using (var cs = new CryptoStream(fs, new ToBase64Transform(),
CryptoStreamMode.Write))
using (var fi = File.Open(filein, FileMode.Open))
{
fi.CopyTo(cs);
}
// the zip file is now stored in base64zip
// and decode
using (FileStream f64 = File.Open(fileout, FileMode.Open))
using (var cs = new CryptoStream(f64, new FromBase64Transform(),
CryptoStreamMode.Read))
using (var fo = File.Open(filein + ".orig", FileMode.Create))
{
cs.CopyTo(fo);
}
// the original file is in my.zip.orig
// use the commandlinetool
// fc my.zip my.zip.orig
// to verify that the start file and the encoded and decoded file
// are the same
}
he code uses standard classes found in System.Security.Cryptography namespace and uses a CryptoStream and the FromBase64Transform and its counterpart ToBase64Transform
I have created the following code
var filename = "wwwroot/Counter/Counter.txt";
var counterStream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
var reader = new StreamReader(counterStream);
var visits = Convert.ToInt32(reader.ReadLine());
visits = visits + 1;
var writer = new StreamWriter(counterStream);
writer.Write(visits);
counterStream.Dispose();
As you will realise, it is a hit counter for a website I am building. I am OK down to the line.
visits = visits + 1
Counter.txt is a file that just contains the one number and the above code has successfully read and updated it. However, the last three lines are not writing anything back to the file. I was half expecting it to write a new line in the file, although obviously I want it to replace the original. I am at a loss as to why it hasn't written anything. Could someone point me in the right direction, please.
Tip, you can use
using(FileStream counterStream=new FileStream())
{
}
Really handy as it will automatically dispose and clean up.
Here is an example that works, though it writes binary
using (FileStream counterStream = new FileStream("counter.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
uint counterVal = 0;
byte[] buffer= new byte[4];
if(counterStream.Read(buffer,0,buffer.Length)>0)
{
counterVal = BitConverter.ToUInt32(buffer, 0);
}
// Increment counter
counterVal++;
buffer = BitConverter.GetBytes(counterVal);
// Reset position (prevent writing a new line)
counterStream.Position = 0;
counterStream.Write(buffer, 0, buffer.Length);
}
But like Yeldar says, this will not work well with webservers due to collisions.
Also I think that your FileShare.None will prevent other users from opening the file, thus missing hits.
You could put it into a database instead, this will make it easier.
I have solved my problem with the following code
const string filename = "wwwroot/Counter/RLSBC.txt";
using (var counterStream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int visits;
using (var reader = new StreamReader(counterStream, System.Text.Encoding.UTF8, true, 4096, true))
{
string line = reader.ReadLine();
int.TryParse(line, out visits);
}
visits = visits + 1;
counterStream.Seek(0L, SeekOrigin.Begin);
using (var writer = new StreamWriter(counterStream))
{
writer.Write(visits);
}
}
I'm running into an error that I can't catch and it should not be there.
if (System.IO.File.Exists (PathToMyFile))
{
try{
FileStream fs = new FileStream(PathToMyFile, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
myFile =Convert.ToBase64String (bytes) ;
}
catch{}
}
For some reason , sometimes I get a exception error that the file does not exist when It most definitely is there. The very first "If statement" even says it is there yet when trying to open the file I sometimes get a massive app crash that the catch does not "catch" .
Like I said, it's a random error, most of the time the code is perfect but the odd occasion seems to throw an error that the app stops working .
First thing is to make sure you close the file\stream
So you can call fs.Close() or using
if (File.Exists(pathToMyFile))
{
try
{
using (var fs = new FileStream(pathToMyFile, FileMode.Open, FileAccess.Read))
{
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32) fs.Length);
br.Close();
fs.Close();
myFile = Convert.ToBase64String(bytes);
}
}
catch
{
// Log exception
}
}
Second, if you need to read the file as string, simply use
if (File.Exists(pathToMyFile))
{
try
{
myFile = File.ReadAllText(pathToMyFile);
}
catch
{
// Log exception
}
}
I have tried retrieving data in the json format as a string and writing it to a file and it worked great. Now I am trying to use MemoryStream to do the same thing but nothing gets written to a file - merely [{},{},{},{},{}] without any actual data.
My question is - how can I check if data indeed goes to memory stream correctly or if the problem occurs somewhere else. I do know that myList does contain data.
Here is my code:
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(List<myClass>));
dcjs.WriteObject(ms, myList);
using (FileStream fs = new FileStream(Path.Combine(Application.StartupPath,"MyFile.json"), FileMode.OpenOrCreate))
{
ms.Position = 0;
ms.Read(ms.ToArray(), 0, (int)ms.Length);
fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
ms.Close();
fs.Flush();
fs.Close();
}
There is a very handy method, Stream.CopyTo(Stream).
using (MemoryStream ms = new MemoryStream())
{
StreamWriter writer = new StreamWriter(ms);
writer.WriteLine("asdasdasasdfasdasd");
writer.Flush();
//You have to rewind the MemoryStream before copying
ms.Seek(0, SeekOrigin.Begin);
using (FileStream fs = new FileStream("output.txt", FileMode.OpenOrCreate))
{
ms.CopyTo(fs);
fs.Flush();
}
}
Also, you don't have to close fs since it's in a using statement and will be disposed at the end.
using (var memoryStream = new MemoryStream())
{
...
var fileName = $"FileName.xlsx";
string tempFilePath = Path.Combine(Path.GetTempPath() + fileName );
using (var fs = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
{
memoryStream.WriteTo(fs);
}
}
//reset the position of the stream
ms.Position = 0;
//Then copy to filestream
ms.CopyTo(fileStream);
The issue is nothing to do with your file stream/ memory stream. The problem is that DataContractJsonSerializer is an OPT IN Serializer. You need to add [DataMemberAttribute] to all the properties that you need to serialize on myClass.
[DataContract]
public class myClass
{
[DataMember]
public string Foo { get; set; }
}
This line looks problematic:
ms.Read(ms.ToArray(), 0, (int)ms.Length);
You shouldn't need to read anything into the memory stream at this point, particularly when you're code is written to read ms into ms.
I'm pretty confident that simply removing this line will fix your problem.
I found a link: http://code.cheesydesign.com/?p=572 about reading PE Files. I am using this code but unfortunately, I get an error on ntHeadersSignature (on reader.ReadUint32). It says that it's unable to read beyond the stream. I wonder why and how to fix this error since I tried with peekchar and read it with readint32, converting it to uint doesn't work. Thank you for your sincere help!
public PeHeaderReader(string filePath)
{
// Read in the DLL or EXE and get the timestamp
using (FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
BinaryReader reader = new BinaryReader(stream);
dosHeader = FromBinaryReader<IMAGE_DOS_HEADER>(reader);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
UInt32 ntHeadersSignature = reader.ReadUInt32(); //HERE IS THE ERROR
fileHeader = FromBinaryReader<IMAGE_FILE_HEADER>(reader);
if (this.Is32BitHeader)
{
optionalHeader32 = FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
}
else
{
optionalHeader64 = FromBinaryReader<IMAGE_OPTIONAL_HEADER64>(reader);
}
imageSectionHeaders = new IMAGE_SECTION_HEADER[fileHeader.NumberOfSections];
for(int headerNo = 0; headerNo < imageSectionHeaders.Length; ++headerNo)
{
imageSectionHeaders[headerNo] = FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
}
}
}