17
votes

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.

1
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
since people are upvoting my answer you can mark my respons as correct maybe ?Cyrus Zei

1 Answers

31
votes

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!