G_Style
G_Style

Reputation: 694

Ruby Dir.chdir not working in loop using unc paths

I'm trying list all files\directories from a users home directory from a list of UNC paths (\servername\HOME\username) in a text file. I'm running Ruby in Windows. I've been using Dir.chdir to change UNC paths which has worked in a variable, but not when I use it with a list in a loop. I think I might have something wrong with my syntax?

First my text file looks something like this:

\\\\servername\\HOME\\username1
\\\\servername\\HOME\\username2
\\\\servername\\HOME\\username3

This is the program that works:

require 'FileUtils'

workingpath = "\\\\servername\\HOME\\username"
filename = '**/*.*'

Dir.chdir workingpath
puts Dir[filename]

This doesn't:

require 'FileUtils'

hostlist = "C:\\home_dirs.txt"
filename = '**/*.*'

File.open(hostlist).each_line do |item|  
Dir.chdir item
puts Dir[filename]
end

The error I keep getting is programname.rb:8:in `open': No such file or directory @ dir_initialize - \\servername\HOME\username (Errno::ENOENT).

Basically the problem is the directory never changes to the unc path. I can't figure out why since it changes directory fine in the first program. What am I missing here?

Upvotes: 0

Views: 668

Answers (2)

G_Style
G_Style

Reputation: 694

Taking out the escape backslashes was only part of the problem. After that, the real error appears:

Errno::EINVAL all pointing to whitespace.

I figured out that it had to be the windows newline hidden characters. I found and used .chomp and that did it! All I did was add it to item like so.

Dir.chdir item.chomp

Upvotes: 1

Paul A Jungwirth
Paul A Jungwirth

Reputation: 24551

You don't need to escape backslashes in your text file, because it is just data, not string literals in code. I would say that is the problem, except strangely your error message has the right number of backslashes, so something doesn't add up.

Upvotes: 0

Related Questions