22

I have a process that fetches a flat file from a mainframe via FTP. This usually works fine for some files. In others, I get: Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8

That's using Net::FTP's gettextfile method. Here is my code:

def find_file( position, value ) # => Value = CLKDRP03.txt, Forget the variable Position

    ftp = Net::FTP.new('IP') # => status 200
    ftp.login('user','pass') # => True

    files = ftp.list('*' + value + '*') # => Obtain the file

    if files[0] != nil

      str_file = files[0].split(" ").last # => Obtain the name of the file. In this case CLKDRP03.txt

      ftp.gettextfile(str_file,'data/input/' + str_file) # => ERROR!, str_file = CLKDRP03.txt
      # => data/input is the path where I put the files from FTP.
      return str_file

    else  
      return false
    end

end

If I comment the line of ftp.gettextfile, the error keeps coming.

Thanks in advance! Sorry for my english.

3
  • Does this help? stackoverflow.com/questions/9905268/…
    – Ollie
    May 28, 2015 at 9:21
  • what line is the exception actually being raised from? Look at the exception trace, and find the line in your source file above that is actually included. is it the line files = ftp.list('*' + value + '*')?
    – jrochkind
    Sep 16, 2015 at 3:28
  • since people are upvoting my answer you can mark my respons as correct maybe ?
    – Cyrus Zei
    Jan 19, 2016 at 8:30

1 Answer 1

39

For anybody that are coming here from google this is how I fixed my encoding error.

right before you declare of open your file add this code

.force_encoding("UTF-8")

so before you declare the file to a variable like this :

csv_file = params[:file].read.force_encoding("UTF-8")

Hope this will help some since I had this problem for a long time, but now it works yay!

4
  • Thank you for posting this! I've been struggling with this error for a while and this fixed it.
    – Ken
    Mar 18, 2016 at 0:09
  • 1
    yeah no problem, same here, I tried to encode it after, but when I refactor my code I noticed that I always tried to encode it after, but never before I assigned it to a variable. Glad it helped you
    – Cyrus Zei
    Mar 18, 2016 at 7:19
  • 1
    Also useful to know, check the default encoding for external things with Encoding.default_external and set it to UTF-8 (if that is what you are primarially dealing with) Encoding.default_external = Encoding::UTF_8. I had a similar problem but with something in a gem, so I couldn't force_encoding too easily. Sep 2, 2016 at 17:25
  • I had the same problem, except that the occasional encoding errors was on file write. The fix for this case is file.write(str.force_encoding("UTF-8"))
    – Jen
    Jun 1, 2017 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.