How can i automatically copy files from one directory to the other

This code copies a file upon reloading

defmodule CopyWeb.PageController do

use CopyWeb, :controller

def index(conn, _params) do

files = move()

render(conn, "index.html", files: files )

end

def move do

  source="C:/Users/john/Desktop/folder-1"

  destination="C:/Users/john/Desktop/folder-2"



  {:ok, data}=File.ls(source)

  

  #copies the  documents  from the source to the destination

  Enum.each(data, fn f->File.cp(source<>"/"<>f, destination<>"/"<>f) end)


 #returns the names of  documents  as a list
  data 

end

What do you mean by “automatically”?

As in as soon a new file gets added to the source folder? You need to use filesystem watches for this. I’m pretty sure there are libraries on hex that are able to wrap those. Not sure though if windows has something like that. As far as I know most systems just fall back to polling on that Plattform.

Also instead of using <> to build your path, you should use Path.join/1,2.

1 Like

yes as soon as a new file gets added to the source folder it should be copied to a new directory. Thanks for your advice.

You can use file_system library to do so.

Basically it requires you to start it, register a listener, and then it will send you messages when files are changed/created/whatever, you need to handle those messages.

There is an example in the README how to do this using a GenServer.

1 Like

Thanks that’s what i needed