i had developed a asp.net c# filewatcher program to monitor a folder.
if there are any modified or new created file, the program will copy those file to another window server shared folder e.g. \192.168.12.12\shared
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Globalization;
using System.Text.RegularExpressions;
namespace FileMonitor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
fileWatcher.Path = @txtPath.Text;
fileWatcher.Filter = txtFilter.Text;
fileWatcher.IncludeSubdirectories = chkSubdirectories.Checked;
}
DateTime lastRead = DateTime.MinValue;
private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != lastRead)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
try
{
string myPath = e.FullPath;
string myFile = e.Name;
System.IO.FileInfo myFileInfo = new System.IO.FileInfo(myFile);
string myAttibs = myFileInfo.Attributes.ToString();
System.IO.File.Copy(myPath, @"\\192.168.12.12\\shared\\" + myFile, true);
lastRead = lastWriteTime;
}
catch (System.IO.IOException ex)
{
System.IO.IOException myex = ex;
}
catch (System.Exception ex)
{
System.Exception myex = ex;
}
}
}
private void fileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != lastRead)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
try
{
string myPath = e.FullPath;
string myFile = e.Name;
System.IO.FileInfo myFileInfo = new System.IO.FileInfo(myFile);
string myAttibs = myFileInfo.Attributes.ToString();
System.IO.File.Copy(myPath, @"\\192.168.12.12\\shared\\" + myFile, true);
lastRead = lastWriteTime;
}
catch (System.IO.IOException ex)
{
System.IO.IOException myex = ex;
}
catch (System.Exception ex)
{
System.Exception myex = ex;
}
}
}
}
}
But I found that i need to access the shared folder once before running the filewatcher program (such as type \192.168.12.12\shared in window explorer, it will prompt me to input login name and password), otherwise the program cannot copy to the shared folder.
How can I pass this login name and password in my program that it can access the shared folder ?
thanks.
The usual way to do this is to give the necessary rights on the shared folder to the user(s) running this type of copy code.
If you cannot do this, you need to use the Win32 functions NetUseAdd or WNetAddConnection2 in order to authenticate to the share (the links point to pinvoke.net that show how to use these functions in C#).