This is a web application
I have 2 pc's: A: 192.168.1.200 and B: 192.168.1.201, I want copy from A to B, this code working is single pc, but it's not working in network.
protected void Button1_Click(object sender, EventArgs e)
{
string sourcePath = #"D:\Source\";
string[] filePaths = Directory.GetFiles(sourcePath, "*.txt");
foreach (string a in filePaths)
{
CopyFiles(a, a.Replace("D:\\Source\\", "D:\\Source1\\New\\"));
//CopyFiles(a, a.Replace("D:\\Source\\", "192.168.1.201\\Source1\\New\\"));
}
}
private bool CopyFiles(string Source, string Destn)
{
try
{
if (File.Exists(Source) == true)
{
File.Copy(Source, Destn);
return true;
}
else
{
Response.Write("Source path . does not exist");
return false;
}
}
catch (FileNotFoundException exFile)
{
Response.Write("File Not Found " + exFile.Message);
return false;
}
catch (DirectoryNotFoundException exDir)
{
Response.Write("Directory Not Found " + exDir.Message);
return false;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
}
Try with:
CopyFiles(a, a.Replace("D:\\Source\\", "\\192.168.1.201\\Source1\\New\\"));
You also need to make sure that the Source1 folder is shared on B, and that you have write access to it.
Did you create the Windows share "Source1" on the receiver machine?
If you did, I would try to mount it on your sender machine and change the code to:
CopyFiles(a, a.Replace("D:\\Source\\", "\\\\192.168.1.201\\Source1\\New\\"));
You have to be allowed to write on the target machine. A work round can be used here, you can make a virtual drive pointing to a network place e.g Z:. Now you can use local notation. But before anything, get sure about permissions on the remote pc.
Related
I have a number of USB drives that I want to copy a folder to.
I can't transfer files at the same time, but only one file at a time.
Although I manage to be directed to a different drive each time, but it is not at the same time.
Where am I wrong?
static void Main(string[] args)
{
string path = #"....";
Parallel.ForEach(
DriveInfo.GetDrives(), drive =>
{
if (drive.DriveType == DriveType.Removable)
{
CloneDirectory(path, drive.Name);
}
}
);
}
private static void CloneDirectory(string root, string dest)
{
foreach (var directory in Directory.GetDirectories(root))
{
//Get the path of the new directory
var newDirectory = Path.Combine(dest, Path.GetFileName(directory));
//Create the directory if it doesn't already exist
Directory.CreateDirectory(newDirectory);
//Recursively clone the directory
CloneDirectory(directory, newDirectory);
}
try
{
foreach (var file in Directory.GetFiles(root))
{
try
{
File.Copy(file, Path.Combine(dest, Path.GetFileName(file)), false);
Console.WriteLine(Path.Combine(dest, Path.GetFileName(file)));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I am wondering on how to create a new directory for a log event file in windows service through c#
I have the following code:
public static void WriteLog(string Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);
//sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.WriteLine(Message);
sw.Flush();
sw.Close();
}
catch{}
}
As the docuemtation states for the Directory.CreateDirectory(path):
Creates all directories and subdirectories in the specified path unless they already exist.
Modified from the example source code:
string path = #"c:\MyDir";
try
{
// Try to create the directory.
Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
There is a really great tutorial on dotnetperls containing example code, exceptions, tips and other useful information about creating directories!
Look up that SO-question to create folders inside the same directory your executable has started, or simple use relative paths instead of absolute ones:
Directory.CreateDirectory("Test");
That way you will never have conflicts about finding the correct path!
File yourFolder= new File("C:/yourFolder");
// if the directory does not exist, create it
if (!yourFolder.exists()) {
System.out.println("Creando directorio: " + yourFolder.getName());
boolean result = false;
try
{
yourFolder.mkdir();
result = true;
}
catch(SecurityException se){
}
if(result) {
System.out.println("Folder created");
}
}
I have the following code which...
Checks if a folder exists
If it exists, check if a file exists
if file exists, read all the lines from the file
once all the line has been read, show the length of the line in a messagebox
Code:
private void button2_Click(object sender, EventArgs e)
{
strPath = #"C:\QRXS";
string strFile = #"C:\QRXS\download.lst";
if (Directory.Exists(strPath))
{
try
{
if (File.Exists(strFile))
{
try
{
ln = File.ReadAllLines(strPath);
}
catch (Exception ex)
{
// inform user or log depending on your usage scenario
MessageBox.Show(ex.Message, "FILE ACCESS");
}
if (ln != null)
{
MessageBox.Show(ln.Length + "");
// do something with lines
}
}
}
catch (Exception ce)
{
MessageBox.Show(ce.Message, "FOLDER ACCESS");
}
}
}
Everytime I run the application (used Run as Administrator as well), the following line keeps being invoked:
MessageBox.Show(ex.Message, "FILE ACCESS");
How can I fix it?
Replace:
File.ReadAllLines(strPath);
with:
File.ReadAllLines(strFile);
Reason: strPath denotes a directory. You're trying to read its contents as if it were a file, and that obviously won't work.
You need to use :
File.ReadAllLines(strFile);
I have a form with a File Watcher to which he transfers to multiple addresses all video files placed in a folder. What is the best option so that when multiple files are added to even be able to perform each transfer in a thread. Here's an example of my code:
DockingBarTransferEntities context = new DockingBarTransferEntities();
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
IEnumerable<Diretorios> directories = context.Diretorios.ToList();
foreach (var destino in directories)
{
try
{
Transfere(e.FullPath,Path.GetFileName(e.FullPath),destino);
}
catch (Exception ex)
{
textBox1.Text += "Error: " + ex.Message;
}
}
}
public void Transfere(string fullPath, string name, Diretorios diretorio)
{
try
{
if (Directory.Exists(diretorio.Caminho))
{
string fileName = Path.GetFileName(fullPath);
fileName = String.Format("{0}\\{1}", diretorio.Caminho, fileName);
FileInfo arquivo = new FileInfo(fullPath);
arquivo.CopyTo(fileName, true);
}
}
catch (Exception ex)
{
}
}
It should be as simple as this:
Task.Factory.StartNew(() => Transfere(e.FullPath, Path.GetFileName(e.FullPath), destino));
instead of calling Transfere directly.
I was reading this article (Can't delete a file using threads) about my problem but things are getting difficult to me.
My problem is really simple, I just want to delete this old file, if I start the method "dlMoveNovaVersao" normally the file is deleted but if I put this on a thread (like bellow) I got "You are not allow". Someone knows what's the problem? (I wanna use thread).
private void verificaVersaoSupervisor_Tick(object sender, EventArgs e)
{
Thread threadConexao = new Thread(threadVerificaConexao);
threadConexao.Start();
}
public void threadVerificaConexao()
{
try
{
Dns.GetHostEntry("www.google.com.br");
if (verificaVersao())
{
try
{
verificaKillSupervisor();
dlMoveNovaVersao();
Application.Exit();
}
catch (Exception)
{ }
}
else
{
Application.Exit();
}
}
catch (Exception)
{ }
}
public void dlMoveNovaVersao()
{
WebClient webClient = new WebClient();
webClient.DownloadFile("Anywebsite", #"c:\temp\supervisor.exe);
try
{
File.Delete(#"c:\Test\supervisor.exe); //This file is always there!
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Just discribe the purpose, My program (Supervisor Starter) check on website if I have an old version of "Supervisor" running (using XML), If it's true my "Supervisor Starter" verify if there is a process called "Supervisor" running and kill it after that "Supervisor Starter" download the new version and run it. (The program is small and the update don't take more then 4 seconds).
The problem start when my "Supervisor Starter" try delete the old version of my program. If I use thread I receive "I haven't permission to access the file", if I use the same method on Form class the file is deleted.
I suspect that you're running the thread while the file is in use. When the thread runs, it runs in parallel with the current thread. Have you ensured that that file is closed?.
Otherwise I think that the thread maybe being created with a credentials that are not yours. But I'm pretty sure this is not the case.
See if this is different for each case
catch (Exception err)
{
MessageBox.Show("User {0}. Message {1}",
System.Security.Principal.WindowsIdentity.GetCurrent().Name,
err.Message);
}
This is my functions for deleting files in threads if the files are in used
private static void Delete(System.IO.FileInfo file)
{
if (file.Exists)
{
int Attempt = 0;
bool ShouldStop = false;
while (!ShouldStop)
{
if (CanDelete(file))
{
file.Delete();
ShouldStop = true;
}
else if (Attempt >= 3)
{
ShouldStop = true;
}
else
{
// wait one sec
System.Threading.Thread.Sleep(1000);
}
Attempt++;
}
}
}
private static bool CanDelete(System.IO.FileInfo file)
{
try
{
//Just opening the file as open/create
using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate))
{
//If required we can check for read/write by using fs.CanRead or fs.CanWrite
}
return false;
}
catch (IOException ex)
{
//check if message is for a File IO
string __message = ex.Message.ToString();
if (__message.Contains("The process cannot access the file"))
return true;
else
throw;
}
}