J*****n 发帖数: 4859 | 1 I am trying to make a class to read and write list, where T is some
struct.
Here r the question:
Read method didn't work out:
An unhandled exception of type 'System.ArgumentException' occurred in
readbin.exe
Additional information: The output char buffer is too small to contain the
decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text.
DecoderReplacementFallback'.
What is the solution?
Thank you.
class BinRW where T:struct
{
private static System.Type _Type;
private static Int32 _Sizeof;
private static byte[] _buffer;
private static GCHandle _h;
private static void StructToByteArray(T element)
{
Marshal.StructureToPtr(element, _h.AddrOfPinnedObject(), false);
}
private static void Set()
{
_Type = typeof(T);
_Sizeof = Marshal.SizeOf(_Type);
_buffer = new byte[_Sizeof];
_h = GCHandle.Alloc(_buffer, GCHandleType.Pinned);
}
public static bool Write(string fn, List list)
{
Set();
if (fn == "")
{
return false;
}
try
{
BinaryWriter bw = new BinaryWriter(File.Open(fn, FileMode.
Create));
foreach (T t in list)
{
StructToByteArray(t);
bw.Write(_buffer);
}
bw.Close();
_h.Free();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public static List Read(string fn)
{
Set();
_h = GCHandle.Alloc(_buffer, GCHandleType.Pinned);
List output = new List();
if (fn == "")
{
return output;
}
T temp;
try
{
BinaryReader br = new BinaryReader(File.Open(fn, FileMode.
Open));
while (br.PeekChar() != -1)
{
_buffer = br.ReadBytes(_Sizeof);
temp = (T)Marshal.PtrToStructure(_h.AddrOfPinnedObject()
, _Type);
output.Add(temp);
}
br.Close();
_h.Free();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
} | c*********e 发帖数: 16335 | 2 参数有错,有没说是第几行? 请贴出完整的错误描述。
【在 J*****n 的大作中提到】 : I am trying to make a class to read and write list, where T is some : struct. : Here r the question: : Read method didn't work out: : An unhandled exception of type 'System.ArgumentException' occurred in : readbin.exe : Additional information: The output char buffer is too small to contain the : decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text. : DecoderReplacementFallback'. : What is the solution?
| n***e 发帖数: 723 | 3 你的T structure定义里面有没有dynamic array?
【在 J*****n 的大作中提到】 : I am trying to make a class to read and write list, where T is some : struct. : Here r the question: : Read method didn't work out: : An unhandled exception of type 'System.ArgumentException' occurred in : readbin.exe : Additional information: The output char buffer is too small to contain the : decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text. : DecoderReplacementFallback'. : What is the solution?
|
|