简体   繁体   中英

On Windows, copy a file to my network folders in Ruby

On windows, I have a file called "test.txt" in C:\\Users\\test\\Documents and I would like to copy it on my network folder with a path (from properties) \\10.2.2.22\\my_folder\\output

I correctly create the file on windows with this line:

File.open("#{Dir.pwd}/output.txt",'a') do |file|
   file.puts "Hello!"
end

Then, I tried to copy it

 sent_to_folder=exec('copy output.txt \\10.2.2.22\my_folder\output')

But I receive the error "The system cannot find the path specified". If I run the same command through the cmd, the file is copied correctly

Any suggestion?

The \\ is the escape char, it must be escaped itself by an escape. So doubling all backslashes should work.

sent_to_folder=exec('copy output.txt \\\\10.2.2.22\\my_folder\\output')

You could alse use FileUtils copy_file and use Unix style forward slashes; Ruby will convert them to Windows style. (I think; can't test)

As mentioned in the accepted answer, you can just use forward slashes in your file path to remove the need to use messy escape characters. Ruby will convert them to backslash.

Use as follows:

require 'FileUtils'

FileUtils.cp('path/to/copy output.txt', '//10.2.2.22/my_folder/output')

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