简体   繁体   中英

File Transfer to c#

I am trying to send a file from python client to a c# server and present it on screen by saving it first and then showing it on my MainWindow. I came across a couple of problems I can't figure out why happen (I'm new to C#) I followed this guide: http://snippetbank.blogspot.com/2014/04/csharp-client-server-file-transfer-example-1.html The problems were:

1. The file was not being saved to my folder.

2. when I used message box to try and detect if it passes all the info it looks like it gets stuck in the middle.

I've been stuck on this for quite some time now but can't figure out what I'm missing

Python code:

def send_file(conn, name):
try:
    full_path = "Output/"+name
    file_to_send = open(full_path, "rb")
    size = os.path.getsize(full_path)
    file_name = name + "\n"
    size_to_send = str(size) + "\n"
    conn.send(size_to_send.encode())
    conn.send(file_name.encode())

    while size > 0:
        data = file_to_send.read(1024)
        conn.send(data)
        size -= len(data)

    file_to_send.close()
    return conn

except IOError:
    print("FILE IS ALREADY OPEN")

C# CODE:

 public static string ReceiveFile(StreamReader reader, TcpClient tcpClient) 
    {
        string folder = @"C:\Users\Roy\Desktop\GUI243\GUI243\";
        // The first message from the client is the file size    
        string cmdFileSize = reader.ReadLine();
        MessageBox.Show(cmdFileSize);
        // The first message from the client is the filename    
        string cmdFileName = reader.ReadLine();
        MessageBox.Show(cmdFileName);
        string full_path = folder + cmdFileName;

        int length = Convert.ToInt32(cmdFileSize);
        byte[] buffer = new byte[length];
        int received = 0;
        int read = 0;
        int size = 1024;
        int remaining = 0;
        // Read bytes from the client using the length sent from the client    
        while (received < length)
        {
            remaining = length - received;
            if (remaining < size)
            {
                size = remaining;
            }

            read = tcpClient.GetStream().Read(buffer, received, size);

            if (read == 0)
            {
                break;
            }

            received += read;
        }
        // Save the file using the filename sent by the client    
        using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
        {
            fStream.Write(buffer, 0, buffer.Length);
            fStream.Flush();
            fStream.Close();
        }
        return full_path;
    }

In your C# code looks like a while cycle is missing, unless you call the function ReceiveFile() iterating somewhere else.

The class StreamReader needs to constantly check the tcp client socket to see if new data has been received because this is how a TCP stream works.

You don't know when the client will connect and send the data so you can't just call the ReceiveFile() function once.

In the example there is a perpetual while (true) cycle that makes that reader.Readline() work:

  while (true)  
        {  
            // Accept a TcpClient    
            TcpClient tcpClient = tcpListener.AcceptTcpClient();  

            Console.WriteLine("Connected to client");  

            StreamReader reader = new StreamReader(tcpClient.GetStream());  

            // The first message from the client is the file size    
            string cmdFileSize = reader.ReadLine();  
            ...
            }

Do you have an equivalent in your code? Also, is not pratical to use MessageBox for debugging purposes.

Try:

Debug.WriteLine ("Expected size is: " + cmdFileSize);

Note you need System.Diagnostics to use that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM