Get Text from File Bytes Without using Temp File - c#

I have a function that is returning the bytes of a text file containing a JSON object to my code, and I need a way to retrieve the contents of that file as a string, then parse it to a C# object.
I have tried using the System.Text.Encoding.Default.GetString() and System.Text.Encoding.UTF8.GetString() methods to parse the byte array, but consistently get a Unexpected character encountered while parsing value: ?. error when I try to deserialize it (more detail below).
If it makes any difference, this is in .NET 6.0.
Example code:
// p is a byte[] being returned from a function earlier in the code.
// To copy the code I'm using exactly, use:
// var p = new byte[] { 255, 254, 123, 0, 34, 0, 114, 0, 101, 0, 99, 0, 116, 0, 115, 0, 34, 0, 58, 0, 91, 0, 93, 0, 44, 0, 34, 0, 116, 0, 101, 0, 120, 0, 116, 0, 34, 0, 58, 0, 34, 0, 34, 0, 125, 0 };
// A text file created with these bytes can be opened like normal.
// Blindly parsing the file bytes to string
var p2 = System.Text.Encoding.Default.GetString(p);
//var p2 = Encoding.UTF8.GetString(p); Doesn't work either
// Fails
dynamic p3 = JsonConvert.DeserializeObject<dynamic>(p2);
Console.WriteLine(p3.text);
Console.WriteLine(p3.rects);
This is the error I get:
Unhandled exception. Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: ?. Path '', line 0, position 0.
Thanks!

Related

How to add string to the front of Text file [duplicate]

This question already has answers here:
Replace one line in a text file
(1 answer)
Fast way to change txt file and save it
(4 answers)
Closed 3 years ago.
This is the text file read by the StreamReader.
500, 120, 60, 0, 350
100, 230, 0, 50, 0
0, 75, 0, 0, 220
3000, 400, 600, 35, 0
350, 200, 100, 80, 250
0, 285, 325, 150, 75
I want to add cities in front of each line, such that it reads like this:
Atlanta: 500, 120, 60, 0, 350
Baltimore: 100, 230, 0, 50, 0
Chicago:0, 75, 0, 0, 220
Denver: 3000, 400, 600, 35, 0
ELY: 350, 200, 100, 80, 250
Fargo: 0, 285, 325, 150, 75
Here's the current code block.
StreamReader sr = new StreamReader("inventory.txt");
String line = sr.ReadToEnd();
Console.WriteLine(line);
If each line is separated by "\n" you could do:
string[] temp = line.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < cityNames.Length; i++)
{
temp[i] += cityNames[i];
}
string result = string.Join(",\n", temp);
return result.Remove(result.Length - 3, 2);

readUInt32BE from nodejs to C#

I have a nodejs buffer:
var buffer = new Buffer([33,49,0,32,0,0,0,0,2,230,69,56,0,1,125,181,99,99,136,122,92,1,99,196,231,90,205,20,75,233,5,103]);
var value = buffer.readUInt32BE(8);
//value == 48645432
I tried read value from C#:
var buffer = new byte[]{33,49,0,32,0,0,0,0,2,230,69,56,0,1,125,181,99,99,136,122,92,1,99,196,231,90,205,20,75,233,5,103};
var value = BitConverter.ToUInt32(buffer, 8)
//value == 944104962
So, I need get value 48645432 from my C# code.
How can I write a method from C# return exact value like readUInt32BE from nodejs?
EDIT: How to get little endian data from big endian in c# using bitConverter.ToInt32 method? not resolve my problem
I resolve my problem
var buffer = new byte[] { 33, 49, 0, 32, 0, 0, 0, 0, 2, 230, 69, 56, 0, 1, 125, 181, 99, 99, 136, 122, 92, 1, 99, 196, 231, 90, 205, 20, 75, 233, 5, 103 };
var value = BitConverter.ToUInt32(buffer, 8);
var rs = BitConverter.ToUInt32(BitConverter.GetBytes(value).Reverse().ToArray(), 0);
//rs = 48645432

IP Header Checksum function in C#

I have Packet byte[]:
byte[] arr = {
17, 34, 51, 68, 85, 102, 0, 20, 34, 24, 129, 17, 8, 0, 69, 0, 0, 95,
88, 117, 0, 0, 128, 17, 136, 254, 10, 61, 50, 135, 172, 49, 112, 37,
9, 129, 6, 110, 0, 75, 244, 143, 4, 1, 0, 67, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 107, 105, 110, 111, 8, 6, 10, 61 ,50, 135,
9, 6, 255, 255, 255, 255, 31, 8, 55, 55, 55, 55, 55, 55, 40, 6, 0, 0, 0,
1, 44, 6, 53, 53, 53, 53, 30, 9, 55, 53, 50, 50, 53, 53, 53 };
What i want to do is try to change my Packet IP Address so i found this function that calculate Checksum and i only want to understand what parameters i need to send to this function (i don't have much knowledge in networking and i started to learn)
private Packet ChangePacketIp(Packet packet, IpV4Address oldIpAddress, IpV4Address newIpAddress)
{
// calculate the checksum
ushort checksum = ComputeHeaderIpChecksum(packet.Buffer, 0, packet.Buffer.Length);
// create header from checksum and data
byte[] header = new byte[packet.Buffer.Length + 2];
Array.Copy(packet.Buffer, 0, header, 2, packet.Buffer.Length);
header[0] = (byte)(checksum >> 8); // high byte first
header[1] = (byte)(checksum & 0xff); // low byte 2n)d
try
{
EthernetLayer ethernet = (EthernetLayer)packet.Ethernet.ExtractLayer();
IpV4Layer ipV4Layer = (IpV4Layer)packet.Ethernet.IpV4.ExtractLayer();
DateTime packetTimestamp = packet.Timestamp;
if (packet.Ethernet.IpV4.Source == oldIpAddress)
{
ipV4Layer.Source = newIpAddress;
ipV4Layer.HeaderChecksum = null;
}
else if (packet.Ethernet.IpV4.Destination == oldIpAddress)
{
ipV4Layer.CurrentDestination = newIpAddress;
ipV4Layer.HeaderChecksum = null;
}
if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
{
TcpLayer tcpLayer = (TcpLayer)packet.Ethernet.IpV4.Tcp.ExtractLayer();
tcpLayer.Checksum = null;
ILayer payload = packet.Ethernet.IpV4.Tcp.Payload.ExtractLayer();
return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, tcpLayer, payload);
}
else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
{
UdpLayer udpLayer = (UdpLayer)packet.Ethernet.IpV4.Udp.ExtractLayer();
udpLayer.Checksum = null;
ILayer payload = packet.Ethernet.IpV4.Udp.Payload.ExtractLayer();
return PacketBuilder.Build(packetTimestamp, ethernet, ipV4Layer, udpLayer, payload);
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
That would be
// calculate the checksum
ushort checksum = XYClassName.ComputeHeaderIpChecksum(arr, 0, arr.Length);
// create header from checksum and data
byte[] header = new byte[arr.Length + 2];
Array.Copy(arr, 0, header, 2, arr.Length);
header[0] = checksum >> 8; // high byte first
header[1] = checksum & 0xff; // low byte 2nd

How to extract an IPv4 address from a Packet? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have this byte[] that represent IPv4 packet:
byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };
And i want to calculate the IPV4 address
Here's a simple parser to examine your byte array:
void Main()
{
byte[] arr = { 0, 48, 136, 21, 69, 131, 0, 24, 231, 253, 174, 161, 8, 0, 69, 0, 0, 52, 2, 31, 64, 0, 128, 6, 230, 22, 212, 25, 99, 74, 202, 177, 16, 121, 194, 156, 0, 119, 160, 128, 75, 200, 249, 141, 210, 78, 80, 24, 64, 252, 130, 182, 0, 0, 65, 82, 84, 73, 67, 76, 69, 32, 51, 52, 13, 10 };
var stream = new MemoryStream(arr, 0, arr.Length);
var reader = new BinaryReader(stream);
Print("Version and header length", reader.ReadByte());
Print("Diff services", reader.ReadByte());
Print("Total length", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("ID", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("Flags and offset", IPAddress.NetworkToHostOrder(reader.ReadInt16()));
Print("TTL", reader.ReadByte());
Print("Protocol", reader.ReadByte());
Print("Checksum", reader.ReadInt16());
Print("Source IP", new IPAddress((int) reader.ReadInt32()));
Print("Destination IP", new IPAddress((int) reader.ReadInt32()));
}
This produces this output:
Version and header length = 0
Diff services = 48
Total length = -30699
ID = 17795
Flags and offset = 24
TTL = 231
Protocol = 253
Checksum = -24146
Source IP = 8.0.69.0
Destination IP = 0.52.2.31
This doesn't seem very right (negative length/checksum? + the protocol should return '6' for TCP or '8' for UDP). You might want to verify your data is correct first.
I wrote this up with code from a tiny project of mine which might help you with future issues. Definitely look at the packet layout on wikipedia, you'll need it with DNS/UDP as well.

string to byte[] array

ok i know this has been beat to death but i can't seam to get all the ones on google here or anyplace to work
i have a string that looks like this
1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
i store this string
each digit has a range from 0 to 254 and the string is almost random
i need to convert this to a byte array because of a hardware
change
this is what the hardware is looking for
hardware.command(DeviceID, byte[]);
i tested the hardware by doing this
hardware.command(1, new byte[] { 0, 0, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38 });
and all was good
each part is a PWM output percentage on the hardware
this updates every 4ms so it has to be somewhat fast
I don't know if this satisfies your performance requirements, but the easiest way would be to use LINQ:
var myByteArray = (from s in myString.Split(',') select byte.Parse(s)).ToArray();
EDIT: I originally wrote byte.Parse(s.Trim()), but Byte.Parse does not mind surrounding whitespace.
Try something like this:
string datastring = "1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0";
byte[] data = datastring.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(s => byte.Parse(s)).ToArray();
or, without LINQ:
var datastring = "1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0";
var tokens = datastring.Split(',');
byte[] data = new byte[tokens.Length];
for (int i = 0; i < tokens.Length; i++) {
data[i] = byte.Parse(tokens[i]);
}
String[] substringArray = String.Split(',');
List<Bytes> listOfBytes = new List<Bytes>();
foreach(String substring in substringArray )
{
substring = substring.Trim();
listOfBytes.Add(Byte.Parse(substring));
}
Byte [] byteTable = listOfBytes.ToArray();

Categories

Resources