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 ?
You would need a
Write(byte[], index, count)method in theStreamWriterclass to do that, but that doesn’t exist. CallingstreamWriter(buffer)is the same asstreamWriter(buffer.ToString()), so that won’t write the contents of the buffer, and usingEncoding.ASCIIto convert the binary content in the buffer to text will change it.Don’t use a
StreamWriterat all. Write to theFileStreaminstead:You should use the variable
xas the length to write rather thanbuffer.Length, as the buffer might not always be completely filled. At least the last block will almost never be a full buffer.