Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How do I transfer files over a local network?

How do I transfer files over a local network?

Scheduled Pinned Locked Moved C#
sysadminquestionhelptutoriallearning
16 Posts 10 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Megidolaon
    wrote on last edited by
    #1

    I've tried a ton of tutorials but none work. Or rather, sooner or later ALL digress and leave the crucial part of transfering a file that isn't pure text. I'm remodeling an app I've previously used to transfer text and project specific objects over a LAN. I'm just having trouble to receive the file and save it again after the transfer (I assume the sending of the file is successful, but of course have no way to actually verify this). Here is the code for my client (sending) app:

        private void Send(string arg)
        {
            TcpClient client = new TcpClient(TB\_Host.Text, (int)UD\_Port.Value);
            FileStream fstream = File.Open(OFD\_File.FileName, FileMode.Open);
            NetworkStream nstream = client.GetStream();
            int data = 0;
    
            while (data > 0)
            {
                data = fstream.ReadByte();
                nstream.WriteByte((byte)data);
            }
    
            fstream.Close();
            nstream.Close();
            client.Close();
        }
    

    And this is the code for the server (receiving) app:

    public void Listen()
    {
    int port = 21112;
    byte[] result = new byte[1024];
    IPAddress address = IPAddress.Parse("127.0.0.1");
    TcpListener listener = new TcpListener(address, port);
    ipEnd = new IPEndPoint(address, port);
    listener.Start();
    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    int f = 0;
    object state = new object();
    socket.Connect(ipEnd);

            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                NetworkStream ns = client.GetStream();
    
                f = socket.Receive(result);
                Invoke(new UpdateDisplayDelegate(UpdateDisplay), result);
            }
        }
    

    The current problem is that the code never reaches the invoke call (the Listen method is on a 2nd thread), which confuses me as there never had been any problem when I transferred text or objects. I tried a SoapFormatter, but while it works great for text and objects, I can't get it to work for files. I also tried using no sockets but a NetworkStream to write into the buffer:

    result = ns.Write(result, 0, int.MaxValue);

    but I always get an ArgumentOutOfRange exception for the size (I used int.MaxValue) parameter. Can you tell me how to

    L J 2 Replies Last reply
    0
    • M Megidolaon

      I've tried a ton of tutorials but none work. Or rather, sooner or later ALL digress and leave the crucial part of transfering a file that isn't pure text. I'm remodeling an app I've previously used to transfer text and project specific objects over a LAN. I'm just having trouble to receive the file and save it again after the transfer (I assume the sending of the file is successful, but of course have no way to actually verify this). Here is the code for my client (sending) app:

          private void Send(string arg)
          {
              TcpClient client = new TcpClient(TB\_Host.Text, (int)UD\_Port.Value);
              FileStream fstream = File.Open(OFD\_File.FileName, FileMode.Open);
              NetworkStream nstream = client.GetStream();
              int data = 0;
      
              while (data > 0)
              {
                  data = fstream.ReadByte();
                  nstream.WriteByte((byte)data);
              }
      
              fstream.Close();
              nstream.Close();
              client.Close();
          }
      

      And this is the code for the server (receiving) app:

      public void Listen()
      {
      int port = 21112;
      byte[] result = new byte[1024];
      IPAddress address = IPAddress.Parse("127.0.0.1");
      TcpListener listener = new TcpListener(address, port);
      ipEnd = new IPEndPoint(address, port);
      listener.Start();
      socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      int f = 0;
      object state = new object();
      socket.Connect(ipEnd);

              while (true)
              {
                  TcpClient client = listener.AcceptTcpClient();
                  NetworkStream ns = client.GetStream();
      
                  f = socket.Receive(result);
                  Invoke(new UpdateDisplayDelegate(UpdateDisplay), result);
              }
          }
      

      The current problem is that the code never reaches the invoke call (the Listen method is on a 2nd thread), which confuses me as there never had been any problem when I transferred text or objects. I tried a SoapFormatter, but while it works great for text and objects, I can't get it to work for files. I also tried using no sockets but a NetworkStream to write into the buffer:

      result = ns.Write(result, 0, int.MaxValue);

      but I always get an ArgumentOutOfRange exception for the size (I used int.MaxValue) parameter. Can you tell me how to

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi, that does not look good. 1.

      Megidolaon wrote:

      while (data > 0)

      the test fails right away, so nothing gets sent. 2.

      Megidolaon wrote:

      data = fstream.ReadByte();

      Now why would you handle one byte at a time? it will take forever on medium-sized files, and even longer on large ones. You are trying to receive 1024 bytes, why not do something similar on the sender side? Use a byte array, Stream.Read(), and make sure to watch the actual number of bytes transferred. 3.

      Megidolaon wrote:

      the code never reaches the invoke call

      see (1) 4.

      Megidolaon wrote:

      I tried a SoapFormatter

      I have no idea why you would use a formatter. Sockets don't care about the data they carry. 5.

      Megidolaon wrote:

      I used int.MaxValue

      If the method needs to allocate a buffer, it will fail to get int.MaxValue bytes of memory, no matter how much RAM your system has. I suggest you try something like this as a sender (not tested!):

      int DIM=1024;
      byte[] bytes=new byte[DIM];
      for(;;) {
      int count=fstream.Read(bytes, 0, DIM);
      if (count==0) break;
      nstream.Write(bytes, 0, count);
      }

      :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

      M 1 Reply Last reply
      0
      • L Luc Pattyn

        Hi, that does not look good. 1.

        Megidolaon wrote:

        while (data > 0)

        the test fails right away, so nothing gets sent. 2.

        Megidolaon wrote:

        data = fstream.ReadByte();

        Now why would you handle one byte at a time? it will take forever on medium-sized files, and even longer on large ones. You are trying to receive 1024 bytes, why not do something similar on the sender side? Use a byte array, Stream.Read(), and make sure to watch the actual number of bytes transferred. 3.

        Megidolaon wrote:

        the code never reaches the invoke call

        see (1) 4.

        Megidolaon wrote:

        I tried a SoapFormatter

        I have no idea why you would use a formatter. Sockets don't care about the data they carry. 5.

        Megidolaon wrote:

        I used int.MaxValue

        If the method needs to allocate a buffer, it will fail to get int.MaxValue bytes of memory, no matter how much RAM your system has. I suggest you try something like this as a sender (not tested!):

        int DIM=1024;
        byte[] bytes=new byte[DIM];
        for(;;) {
        int count=fstream.Read(bytes, 0, DIM);
        if (count==0) break;
        nstream.Write(bytes, 0, count);
        }

        :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

        M Offline
        M Offline
        Megidolaon
        wrote on last edited by
        #3

        ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

        K L H F P 7 Replies Last reply
        0
        • M Megidolaon

          ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

          K Offline
          K Offline
          Keith Barrow
          wrote on last edited by
          #4

          ... What? All he did was provide a good critique that you should learn from and some code that has more than a snowball's chance of working.

          Sort of a cross between Lawrence of Arabia and Dilbert.[^]
          -Or-
          A Dead ringer for Kate Winslett[^]

          M 1 Reply Last reply
          0
          • M Megidolaon

            ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

            H Offline
            H Offline
            Henry Minute
            wrote on last edited by
            #5

            Megidolaon wrote:

            All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

            Except that yours does nothing, that you can verify anyway. You were given a reason for this, have you investigated it?

            Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

            1 Reply Last reply
            0
            • M Megidolaon

              ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              Megidolaon wrote:

              int data = 0; while (data > 0) ...

              and how many iterations will this loop execute in your opinion? :doh:

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

              Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

              K 1 Reply Last reply
              0
              • L Luc Pattyn

                Megidolaon wrote:

                int data = 0; while (data > 0) ...

                and how many iterations will this loop execute in your opinion? :doh:

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

                K Offline
                K Offline
                Keith Barrow
                wrote on last edited by
                #7

                I'll give him a clue: it's the same value as data. Lets see if he cracks the code :-)

                Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                -Or-
                A Dead ringer for Kate Winslett[^]

                1 Reply Last reply
                0
                • M Megidolaon

                  ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

                  F Offline
                  F Offline
                  fjdiewornncalwe
                  wrote on last edited by
                  #8

                  My vote of 1... Try doing a bit of the thinking yourself. He provided you exactly what you need to get it going. All you have to do is follow instructions.

                  I wasn't, now I am, then I won't be anymore.

                  1 Reply Last reply
                  0
                  • M Megidolaon

                    ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

                    P Offline
                    P Offline
                    Pete OHanlon
                    wrote on last edited by
                    #9

                    All you did was provide code that couldn't possibly work. Luc provided reasons why, and a practical suggestion on how to take your code forwards. Luc's comments were valid, pertinent and usable - if you think his code does the same as yours, I suggest that you need to step through the code line by line. BTW - had you actually bothered to debug your application, you'd have spotted that you could never step into the loop.

                    I'm not a stalker, I just know things. Oh by the way, you're out of milk.

                    Forgive your enemies - it messes with their heads

                    My blog | My articles | MoXAML PowerToys | Onyx

                    1 Reply Last reply
                    0
                    • M Megidolaon

                      ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #10

                      Megidolaon wrote:

                      and post code that does exactly the same thing as mine.

                      With one major difference, your code will never work, Luc's always will.

                      Just say 'NO' to evaluated arguments for diadic functions! Ash

                      D 1 Reply Last reply
                      0
                      • L Lost User

                        Megidolaon wrote:

                        and post code that does exactly the same thing as mine.

                        With one major difference, your code will never work, Luc's always will.

                        Just say 'NO' to evaluated arguments for diadic functions! Ash

                        D Offline
                        D Offline
                        dan sh
                        wrote on last edited by
                        #11

                        Signature material. Hijacked. :)

                        "Your code will never work, Luc's always will.", Richard MacCutchan[^]

                        L 1 Reply Last reply
                        0
                        • D dan sh

                          Signature material. Hijacked. :)

                          "Your code will never work, Luc's always will.", Richard MacCutchan[^]

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #12

                          :thumbsup: Fame at last! :cool:

                          Just say 'NO' to evaluated arguments for diadic functions! Ash

                          1 Reply Last reply
                          0
                          • M Megidolaon

                            ...what? All you did is provide some vague comments that are unusable and post code that does exactly the same thing as mine.

                            _ Offline
                            _ Offline
                            _Erik_
                            wrote on last edited by
                            #13

                            I have a question here: Do you want somebody to do your job or do you want to learn? If you want somebody to do your job, then look for a professional, ask him to do the job and pay him for it. If you want to learn then read again Luc's answer and try to apply his advices. Additionally, you might say "Thank you for your time" or nothing at all, but this kind of reply is a great invitation to blacklist you and do never answer any other of your questions.

                            1 Reply Last reply
                            0
                            • M Megidolaon

                              I've tried a ton of tutorials but none work. Or rather, sooner or later ALL digress and leave the crucial part of transfering a file that isn't pure text. I'm remodeling an app I've previously used to transfer text and project specific objects over a LAN. I'm just having trouble to receive the file and save it again after the transfer (I assume the sending of the file is successful, but of course have no way to actually verify this). Here is the code for my client (sending) app:

                                  private void Send(string arg)
                                  {
                                      TcpClient client = new TcpClient(TB\_Host.Text, (int)UD\_Port.Value);
                                      FileStream fstream = File.Open(OFD\_File.FileName, FileMode.Open);
                                      NetworkStream nstream = client.GetStream();
                                      int data = 0;
                              
                                      while (data > 0)
                                      {
                                          data = fstream.ReadByte();
                                          nstream.WriteByte((byte)data);
                                      }
                              
                                      fstream.Close();
                                      nstream.Close();
                                      client.Close();
                                  }
                              

                              And this is the code for the server (receiving) app:

                              public void Listen()
                              {
                              int port = 21112;
                              byte[] result = new byte[1024];
                              IPAddress address = IPAddress.Parse("127.0.0.1");
                              TcpListener listener = new TcpListener(address, port);
                              ipEnd = new IPEndPoint(address, port);
                              listener.Start();
                              socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                              int f = 0;
                              object state = new object();
                              socket.Connect(ipEnd);

                                      while (true)
                                      {
                                          TcpClient client = listener.AcceptTcpClient();
                                          NetworkStream ns = client.GetStream();
                              
                                          f = socket.Receive(result);
                                          Invoke(new UpdateDisplayDelegate(UpdateDisplay), result);
                                      }
                                  }
                              

                              The current problem is that the code never reaches the invoke call (the Listen method is on a 2nd thread), which confuses me as there never had been any problem when I transferred text or objects. I tried a SoapFormatter, but while it works great for text and objects, I can't get it to work for files. I also tried using no sockets but a NetworkStream to write into the buffer:

                              result = ns.Write(result, 0, int.MaxValue);

                              but I always get an ArgumentOutOfRange exception for the size (I used int.MaxValue) parameter. Can you tell me how to

                              J Offline
                              J Offline
                              jschell
                              wrote on last edited by
                              #14

                              Megidolaon wrote:

                              Or is this approach wrong in the first place?

                              As you said it is a local network so why not just use the OS to do the transfer? And if there is some security reason for that then just set up a ftp server and client.

                              1 Reply Last reply
                              0
                              • K Keith Barrow

                                ... What? All he did was provide a good critique that you should learn from and some code that has more than a snowball's chance of working.

                                Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                                -Or-
                                A Dead ringer for Kate Winslett[^]

                                M Offline
                                M Offline
                                Megidolaon
                                wrote on last edited by
                                #15

                                Critique? I did not ask for critique, I asked for help. Which he pretended he gave, but actually did not give at all.

                                K 1 Reply Last reply
                                0
                                • M Megidolaon

                                  Critique? I did not ask for critique, I asked for help. Which he pretended he gave, but actually did not give at all.

                                  K Offline
                                  K Offline
                                  Keith Barrow
                                  wrote on last edited by
                                  #16

                                  Look, if you aren't up to working out what he said, that's your problem. The answer he have was helpful: Your code couldn't possibly run, was inefficient and poorly designed. He covered each of those points. He even gave you a sample of code that fixes those problems. I suggest you read the other comments and figure out why you are wrong, rather than attempting flip answers.

                                  Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                                  -Or-
                                  A Dead ringer for Kate Winslett[^]

                                  1 Reply Last reply
                                  0
                                  Reply
                                  • Reply as topic
                                  Log in to reply
                                  • Oldest to Newest
                                  • Newest to Oldest
                                  • Most Votes


                                  • Login

                                  • Don't have an account? Register

                                  • Login or register to search.
                                  • First post
                                    Last post
                                  0
                                  • Categories
                                  • Recent
                                  • Tags
                                  • Popular
                                  • World
                                  • Users
                                  • Groups