For some reasons, I want to write a GUID as ID into one file for save, and delete the id before opening the file.
static void Main(string[] args)
{
string id = "b669fd8c904d48e0945c16cac1dc5ed9";
byte[] idbyte = UnicodeEncoding.Default.GetBytes(id);
FileStream input = new FileStream(@"C:\test.xlsx", FileMode.Open, FileAccess.Read);
FileStream output = new FileStream(@"C:\test1.xlsx", FileMode.OpenOrCreate, FileAccess.Write);
CopyStream(input, output);
// add id with byte[] at the end of the file
output.Write(idbyte, 0, idbyte.Length);
output.Close();
input.Close();
FileStream input1 = new FileStream(@"C:\test1.xlsx", FileMode.Open, FileAccess.Read);
FileStream output1 = new FileStream(@"C:\test2.xlsx", FileMode.OpenOrCreate, FileAccess.Write);
int SizeOfBuffer = 1024 * 16;
try
{
byte[] buffer = new byte[SizeOfBuffer];
byte[] bufferLast = new byte[SizeOfBuffer];
int read;
int Nextread;
while ((read = input1.Read(buffer, 0, buffer.Length)) > 0)
{
if ((Nextread = input1.Read(bufferLast, 0, buffer.Length)) > 0)
{
output1.Write(buffer, 0, read);
output1.Write(bufferLast, 0, Nextread);
}
else // delete id with byte[]
{
byte[] buffer2 = new byte[SizeOfBuffer];
for (int i = 0; i < read - idbyte.Length; i++)
{
buffer2[i] = buffer[i];
}
output1.Write(buffer2, 0, buffer2.Length);
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
output1.Close();
input1.Close();
Console.ReadLine();
}
private static void CopyStream(Stream input, Stream output)
{
int SizeOfBuffer = 1024 * 16;
try
{
byte[] buffer = new byte[SizeOfBuffer];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
But when I open the C:\test2.xlsx, excel shows error: “Excel found unreadable content in ‘test2.xlsx'”!
How to solve this problem ?
The following works for me. As you can see I did a bit of reorganizing so I could more easily tell what I was doing and to simplify the tests. Let me know if you have any questions.