I am working on a file-watcher project using C# and I am trying to copy changes files into new created files, but I am getting the error: Illegal characters in the path as shown below
I think the problem comes from the white space before .4, which I have underlined in yellow. I am trying to get rid of this white space but I can't. The code is down below
private void OnChanged(object source, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed || e.ChangeType == WatcherChangeTypes.Created)
{
String targetname = null;
String fn = "";
try
{
bool copy = true;
targetname = GetShortcutTarget(e.FullPath);
if (targetname == null)
{
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
else
{
c += 1;
fn = targetname.Replace('\\', '_').Replace(":", "_c_");
DateTime lmt = File.GetLastWriteTime(targetname);
if (lastSeen.ContainsKey(targetname))
{
if (lastSeen[targetname] < lmt)
{
copy = true;
}
else
{
copy = false;
}
}
else
{
lastSeen[targetname] = lmt;
copy = true;
}
if (copy)
{
Console.WriteLine($"Filec: {e.FullPath} {targetname} {e.ChangeType}");
//HERE
System.IO.File.Copy(targetname, $"{_lfile}\\{fn}.{c}", true);
// Only keep copy if copy worked
latest[fn] = c;
}
else
{
Console.WriteLine($"Have {e.FullPath} {targetname}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Failure to copy {e.FullPath} {targetname} {$"{_lfile}\\{fn}.{c}"} {ex.Message}");
}
}
else
{
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
}
I have noted a "HERE" comment to show you where the name of the file is created. I have tried many methods like Trim, Replace but it doesn't work. Can you please help me? I would be really grateful.
namespace FileWatcher
{
class Program
{
static void Main(string[] args)
{
String userName;
String expt;
if (args.Length < 2)
{
Console.WriteLine($"FileWatcher <user> <exptName>");
Console.WriteLine($"Captures files into /temp/<exptName>-log and /temp/<exptName>-files");
userName = "lashi";
expt = "expt1";
}
else
{
userName = args[0];
expt = args[1];
}
String lexpt = $"c:\\temp\\{expt}-log";
String fexpt = $"c:\\temp\\{expt}-file";
if (!Directory.Exists(fexpt))
{
Directory.CreateDirectory(fexpt);
}
if (!Directory.Exists(lexpt))
{
Directory.CreateDirectory(lexpt);
}
Watcher w = new Watcher(lexpt, fexpt, userName);
w.Watch();
}
}
class Watcher
{
Dictionary<String, int> latest = new Dictionary<String, int>();
String _username;
String _ext;
String _lfile;
String _ffile;
int c = 0;
Dictionary<String, DateTime> lastSeen;
public Watcher(String lfile, String fFile, String uName)
{
_username = uName;
_ext = "*";
_lfile = lfile;
_ffile = fFile;
lastSeen = new Dictionary<string, DateTime>();
Console.CancelKeyPress += copyFiles;
}
public void copyFiles(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Acting on ctrl-c");
copyFiles();
}
public void copyFiles()
{
foreach (KeyValuePair<string, int> entry in latest)
{
try
{
System.IO.File.Copy($"{_lfile}\\{entry.Key}.{entry.Value}", $"{ _ffile}\\{entry.Key}", true);
}
catch (Exception e)
{
Console.WriteLine($"Failure to take last copy {entry.Key} {entry.Value}");
}
}
}
public void Watch()
{
using (FileSystemWatcher watcher = new FileSystemWatcher($"C:\\Users\\{_username}\\AppData\\Roaming\\Microsoft\\Windows\\Recent", _ext))
{
// watcher.Path = args[1];
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Only watch text files.
// watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = false;
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
// After a q then
}
Failure to copy C:\Users\lashi\AppData\Roaming\Microsoft\Windows\Recent\MSIX+VHD.docx.lnk C:\Users\lashi\Desktop\Klera_Internship\MSIX+VHD.docx c:\temp\expt1-log\C_c__Users_lashi_Desktop_Klera_Internship_MSIX+VHD.docx .1 Illegal characters in path.