I'm trying to write an apk file from a filestream to my android storage. I'm using Unity 3D with C#.
When testing on the PC I can send requests to my server (whichis also a c# console application), and save the apk file that my server sends me. It is a complete file and can be installed on any android.
However, when I build the project for android, it won;t wriet all the data to the storage device. here is the relevant code:
string apkFilePath = Application.persistentDataPath;
apkFilePath = apkFilePath + "/new.apk";
public void Receive()
{
byte[] RecData = new byte[BufferSize];
int RecBytes;
for (; ; )
{
string Status = string.Empty;
try
{
int totalrecbytes = 0;
if(File.Exists(apkFilePath))
{
File.Delete(apkFilePath);
}
FileStream Fs = new FileStream(apkFilePath, FileMode.Create, FileAccess.Write);
while ((RecBytes = ns.Read(RecData, 0, RecData.Length)) > 0)
{
if (RecBytes >= BufferSize)
{
print(RecBytes);
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
Fs.Flush();
}
if(RecBytes < BufferSize && RecBytes > 0)
{
print(RecBytes);
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
Fs.Flush();
break;
}
}
print("OUT OF LOOP");
//Fs.Flush();
Fs.Dispose();
Fs.Close();
quit = true;
break;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//netstream.Close();
}
}
}
Any suggestions why it works for my PC but not on Android?
Related
I am uploading a 10GB file to my ftp server using c# ftpwebrequest. How can the rate of transfer be calculated ?
The following is the code:
FileStream fs = null;
Stream rs = null;
try
{
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = ftpServer;
Console.WriteLine("Start Time: {0}", DateTime.Now);
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
rs = requestObj.GetRequestStream();
byte[] buffer = new byte[40960];
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, read);
}
rs.Flush();
}
catch (Exception ex)
{
Console.WriteLine("File upload/transfer Failed.\r\nError Message:\r\n" + ex.Message);
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (rs != null)
{
rs.Close();
rs.Dispose();
}
}
Console.WriteLine("End Time: {0}", DateTime.Now);
Console.WriteLine("Exiting the application.. press any key to continue");
Console.ReadLine();
The upload speed was low so I bumped up the Buffer Size to 40960 after referring to some articles. The speed has increased a bit.
Please explain the solution as well for my understanding as I am a beginner. Thanks in advance.
I have a big problem with copying files. When I copy files by File.Copy or FileStream, executing code kill my server. I copied ten files from remote directory to temp dir. The biggest file have around 20MB and cause error
At first I tried File.Copy(), when I run code, server collapsed.
foreach (string file in customerFiles)
{
File.Copy(file, tempOnFile);
}
Same server collapsed happened when I tried this code in foreach:
byte[] buffer;
FileStream fileReader = new FileStream(file, FileMode.Open, FileAccess.Read);
try
{
int bufferSize = (int)fileReader.Length;
buffer = new byte[bufferSize];
int count, sum = 0;
while ((count = fileReader.Read(buffer, sum, bufferSize - sum)) > 0 )
{
sum += count;
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
fileReader.Flush();
fileReader.Close();
}
//Write
string fileOnTemp = pathToTemp + fileName;
FileStream fileWriter = new FileStream(fileOnTemp, FileMode.CreateNew, FileAccess.Write);
try
{
fileWriter.Write(buffer, 0, buffer.Length);
}
catch(Exception ex)
{
throw ex;
}
finally
{
fileWriter.Flush();
fileWriter.Close();
}
Please Help! Thank you,
Michal
I'm trying to send file from TCP client to listener. Its all working but after the file is sent, the client is disconnecting from the server. Here is the code I'm currently using for the client:
public static void SendFile(FileInfo file)
{
try
{
long size = file.Length;
using (NetworkStream ns = client.GetStream())
{
using (FileStream Fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
{
int num;
byte[] buffer = new byte[Fs.Length];
while ((num = Fs.Read(buffer, 0, buffer.Length)) != 0)
{
ns.Write(buffer, 0, num);
}
Fs.Close();
ns.Close();
}
}
FileInfo p_c = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\destfile.bin");
p_c.Delete();
} catch(Exception ex)
{
}
}
and for the server:
using (NetworkStream ns = new NetworkStream(current))
{
using (FileStream Fs = new FileStream(full_path, FileMode.OpenOrCreate, FileAccess.Write))
{
while ((RecBytes = ns.Read(RecData, 0, RecData.Length)) > 0)
{
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
}
{
Fs.Close();
ns.Close();
Console.WriteLine("File received. Path: {0}", full_path);
}
}
Calling NetworkStream.Close() or NetworkStream.Dispose (at the end of the using clause) will terminate the connection.
If you want to keep the socket open, use the NetworkStream(Socket, bool) constructor and and pass false as the second parameter.
I have an active audio recording happening in WAV format with NAudio Library.
private void RecordStart() {
try {
_sourceStream = new WaveIn {
DeviceNumber = _recordingInstance.InputDeviceIndex,
WaveFormat =
new WaveFormat(
44100,
WaveIn.GetCapabilities(_recordingInstance.InputDeviceIndex).Channels)
};
_sourceStream.DataAvailable += SourceStreamDataAvailable;
if (!Directory.Exists(_recordingInstance.AudioFilePath)) {
Directory.CreateDirectory(_recordingInstance.AudioFilePath);
}
WaveFileWriter _waveWriter = new WaveFileWriter(
_recordingInstance.AudioFilePath + _recordingInstance.AudioFileName,
_sourceStream.WaveFormat);
_sourceStream.StartRecording();
}
catch (Exception exception) {
Log.Error("Recording failes", exception);
}
}
private void SourceStreamDataAvailable(object sender, WaveInEventArgs e) {
if (_waveWriter == null) return;
_waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
_waveWriter.Flush();
}
I want to copy the latest available content to another location. The copied file should be in WAV format, and should be able to play the available duration. Update the destination file, whenever more content is available.
I have Tried the following sample code (using NAudio) with a static WAV file, but the solution is not working.
The resulting WAV file created is corrupted - not in the correct format.
using (WaveFileReader reader = new WaveFileReader(remoteWavFile))
{
byte[] buffer = new byte[reader.Length];
int read = reader.Read(buffer, 0, buffer.Length);
}
When the recording is in progress, the code throws an exception "File is in use by another application".
I have solved the problem with help of NAudio Library itself.
When we only use the WaveFileReader class of NAudio. It will throw the exception - "file is in use by another application".
So I had to create a file stream, which opens the source file - live recording file, with File.Open(inPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) then pass this stream as an input of WaveFileReader.
Then create a WaveFileWritter class of NAudio, with the same WavFormat of the reader.
copied below is the code, i have used.
public static void CopyWavFile(string inPath, string outPath){
using (var fs = File.Open(inPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
using (var reader = new WaveFileReader(fs)){
using (var writer = new WaveFileWriter(outPath, reader.WaveFormat)){
reader.Position = 0;
var endPos = (int)reader.Length;
var buffer = new byte[1024];
while (reader.Position < endPos){
var bytesRequired = (int)(endPos - reader.Position);
if (bytesRequired <= 0) continue;
var bytesToRead = Math.Min(bytesRequired, buffer.Length);
var bytesRead = reader.Read(buffer, 0, bytesToRead);
if (bytesRead > 0){
writer.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
This question may be very hard to answer or perhaps somebody knows a common reason.
I have 1 server, 5 clients;
Socket client
Socket listener
Every 5000 MS the client checks for a file on the server (Which is Windows 7)via socket, if found the client received the file via socket.
I understand only Windows Server can process more than two asynch file transfers at a time.
My issue is that, randomly the client begins to receive the file. All clients generally work fine. Once in a while, a client will stop receiving the file partthrough and not complete the file transfer and my client program just hangs and never finishes.
I can NOT reproduce this on development environment. I have tested it with half-gig files, 100's of sends and I never get an error.
My question is , is it possible that there is some protocol on Windows 7 that is stopping my file send from the server.
My Receive call back for the client is quite lengthy, but here it is. I do not believe the problem to be within the code.
Any help would be greatly appreciated. My boss is about to have my neck :(
private static void ReceiveCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
state.totalBytesRead += bytesRead;
if (bytesRead > 0)
{
if (state.flag == 0)
{
if (state.totalBytesRead >= 8)
{
// we know we put the msgLen / prefixLen as the first 8 bytes on the stream
state.msgLen = BitConverter.ToInt32(state.buffer, 0);
state.prefixLen = BitConverter.ToInt32(state.buffer, 4);
state.flag = 1;
// good to process the first 2 integer values on the stream
//state.sb.Append(Encoding.ASCII.GetString(state.buffer, 8, bytesRead));
int prefixRequestBytes = state.prefixLen;
if (prefixRequestBytes > StateObject.BufferSize)
prefixRequestBytes = StateObject.BufferSize;
state.lastSendByteCount = prefixRequestBytes;
state.totalBytesRead = 0;
// start re-writing to the begining of the buffer since we saved
client.BeginReceive(state.buffer, 0, prefixRequestBytes, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
else
{
int bytesToSend = state.lastSendByteCount - bytesRead;
state.lastSendByteCount = bytesToSend;
// need to receive atleast first 8 bytes to continue
// Get the rest of the data.
client.BeginReceive(state.buffer, state.totalBytesRead, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
if (state.flag == 1)
{
// we are expexing to process the prefix
if (state.totalBytesRead >= state.prefixLen)
{
// we are good to process
// Lets always assume that our prefixMsg can fit into our prefixbuffer ( we wont send greater than prefixbuffer)
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.prefixLen));
string prefixMsg = state.sb.ToString();
if (!String.IsNullOrEmpty(prefixMsg))
{
state.cmd = parseXml("CMD", prefixMsg);
state.fName = parseXml("FNAME", prefixMsg);
// File requester should never get a del command
//if (state.cmd == "DEL")
//{
// Console.WriteLine("Processing 'DEL' command..");
// // delete the file
// string filePath = "C:\\" + locationFolder + "\\" + state.fName;
// if (System.IO.File.Exists(filePath))
// {
// System.IO.File.Delete(filePath);
// }
// Console.WriteLine("Deleted file");
// // receiveDone.Set();
// requestTimer.Start();
// return;
//}
//else
if (state.cmd == "SND")
{
Console.WriteLine("Processing 'SND' command..");
// let it rip
if (state.msgLen == 0) // no files
{
Console.WriteLine("No files on server");
requestTimer.Start();
return;
}
}
}
state.receivedPath = importTempFolder + state.fName;
// receive the rest of the file
if (System.IO.File.Exists(state.receivedPath))
{
Console.WriteLine("Deleting temp file: " + state.receivedPath + " for re-write");
System.IO.File.Delete(state.receivedPath);
}
state.flag++;
int msgRequestBytes = state.msgLen;
if (msgRequestBytes > StateObject.BufferSize)
msgRequestBytes = StateObject.BufferSize;
state.lastSendByteCount = msgRequestBytes;
state.totalBytesRead = 0;
// should be good to process the msg now
// start re-writing to the begining of the buffer since we saved
client.BeginReceive(state.buffer, 0, msgRequestBytes, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
else
{
int bytesToSend = state.lastSendByteCount - bytesRead;
state.lastSendByteCount = bytesToSend;
// request the rest of the prefix
// Get the rest of the data.
client.BeginReceive(state.buffer, state.totalBytesRead, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
// we are expecting to process the file
if (state.flag > 1)
{
if (state.totalBytesRead >= state.msgLen)
{
Console.WriteLine("Writing final {0} bytes to server", bytesRead);
using (FileStream fs = new FileStream(state.receivedPath, FileMode.Append, FileAccess.Write))
using (BinaryWriter writer = new BinaryWriter(fs))
{
//BinaryWriter writer = new BinaryWriter(File.Open(state.receivedPath, FileMode.Append, FileAccess.Write, FileShare.None));
writer.Write(state.buffer, 0, bytesRead);
fs.Flush();
// writer.Close();
}
// GC.Collect();
// if temp folder exists, import will exists because its inside it
string destFile = importFolder + state.fName;
if (System.IO.File.Exists(destFile))
{
Console.WriteLine("Deleting file for re-write in importin: \n" + destFile);
System.IO.File.Delete(destFile);
}
Console.WriteLine("Moving file: \n" + state.receivedPath);
System.IO.File.Copy(state.receivedPath, destFile);
Console.WriteLine("Deleting file from temp: \n" + state.receivedPath + importTempFolder + state.fName);
System.IO.File.Delete(state.receivedPath);
if (state.cmd == "SND")
{
Console.WriteLine("Sending 'DEL' command.");
SendDeleteResponse(client, state.fName);
Console.WriteLine("Finished reading to file: " + state.receivedPath);
// receiveDone.Set();
requestTimer.Start();
return;
}
Console.WriteLine("Finished reading file");
client.Shutdown(SocketShutdown.Both);
client.Close();
// receiveDone.Set();
requestTimer.Start();
}
else
{
//Console.WriteLine("Reading {0} bytes from server...", bytesRead);
// Padd these bytes
using (FileStream fs = new FileStream(state.receivedPath, FileMode.Append, FileAccess.Write))
using (BinaryWriter writer = new BinaryWriter(fs))
{
//BinaryWriter writer = new BinaryWriter(File.Open(state.receivedPath, FileMode.Append, FileAccess.Write, FileShare.None));
writer.Write(state.buffer, 0, bytesRead);
fs.Flush();
// writer.Close();
}
// GC.Collect();
// get how many more bytes are left to read
int bytesToSend = state.msgLen - bytesRead;
if (bytesToSend > StateObject.BufferSize)
bytesToSend = StateObject.BufferSize;
client.BeginReceive(state.buffer, 0, bytesToSend, 0, new AsyncCallback(ReceiveCallback), state);
return;
}
}
}
else
{
// All the data has arrived;
}
}
catch (Exception e)
{
Console.WriteLine("HERE5 " + e.Message);
client.Close();
// receiveDone.Set();
requestTimer.Start();
return;
}
}