问题
Actually I am copying an exe file over sockets. I am able to copy a text using StreamWriter
Class but i used the same code for copying a exe file , it created a exe file with the desired name but I cannot run it.
"This app cannot run on your PC". I have Windows 8 x64, that is irrelevant.
static void Main(string[] args)
{
TcpClient tcpclient = new TcpClient();
tcpclient.Connect("localhost", 20209);
NetworkStream stm = tcpclient.GetStream();
byte[] buffer = new byte[1024];
var fs = File.Open("F:/aki/RMI/akshay.exe", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var streamWriter = new StreamWriter(fs);
int x;
while ((x=stm.Read(buffer, 0, 1024))>0)
{
**A** streamWriter.Write(buffer);
**B** //streamWriter.Write(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
}
streamWriter.Close();
fs.Close();
Thread.Sleep(2000);
Console.WriteLine("Waiting");
//Console.ReadLine();
tcpclient.Close();
}
I tried both A and B methods, B works for text file but not for an exe file. Any solutions?
Or I have to use any other Writer Class for exe files ?
回答1:
You would need a Write(byte[], index, count)
method in the StreamWriter
class to do that, but that doesn't exist. Calling streamWriter(buffer)
is the same as streamWriter(buffer.ToString())
, so that won't write the contents of the buffer, and using Encoding.ASCII
to convert the binary content in the buffer to text will change it.
Don't use a StreamWriter
at all. Write to the FileStream
instead:
while ((x = stm.Read(buffer, 0, 1024)) > 0) {
fs.Write(buffer, 0, x);
}
You should use the variable x
as the length to write rather than buffer.Length
, as the buffer might not always be completely filled. At least the last block will almost never be a full buffer.
回答2:
A StreamWriter is a TextWriter. Can't you just do:
fs.Write(buffer, 0, buffer.Length);
来源:https://stackoverflow.com/questions/13101967/how-to-write-an-exe-file-using-c-sharp-code-with-streamwriter