Copy file to directory - c#

Is there no .NET library call for copying a file to a directory? All library calls I found (e.g. File.Copy() or FileInfo.CopyTo()) do only support copying a file to another fully specified file.
string file = "C:\Dir\ect\ory\file.txt";
string dir = "C:\Other\Directory";
File.Copy(file, dir); // does not work, requires filename
Is there a library call? If no, what's the best way to write my own utility, do I really have to use Path.GetFileName()?

do I really have to use Path.GetFileName()?
Exactly:
string destination = Path.Combine(dir, Path.GetFileName(file));
Directory.CreateDirectory(dir);
File.Copy(file, destination);

Try this example
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
}

Related

Windows service acces denied to path 192.168.1.XX

My windows service copy a file from antoher PC in the same network.
This is the code
string fileName = "test.txt";
string sourcePath = #"\\192.168.1.XX\Users\utente\Desktop\prova\";
string targetPath = #"C:\Users\IDEA\source\repos\BotterService\bin\Debug";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.Directory.CreateDirectory(targetPath);
try
{
File.Copy(sourceFile, destFile);
}
catch (Exception ex)
{
Debug("EXCEPTION: " + ex.Message);
}
From my PC I have all permiss to read and write test.txt file. Infact I can read, write and save this file.
I got the error permission denied to 192.168.1.XX\Users\utente\Desktop\prova\
Thanks

Xamarin.Forms Deleting Files at Runtime iOS

I need to store a byte[] in memory. I need to access it later. The byte[] represents a video. The following code will allow the file to be written to memory, as well as accessed from memory. When the remove method shown below is called, it can still be accessed later.
I have checked that the pathname is the same.
public void StoreVideo(byte[] video, string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
Directory.CreateDirectory(directoryname);
var path = Path.Combine(directoryname, filename);
File.WriteAllBytes(path, video);
}
public void RemoveVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
File.Delete(filename);
}
public byte[] GetVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
if(File.Exists(path))
{
return File.ReadAllBytes(path);
}
return null;
}
The answer to this was just a small brain fart on the path being passed to the File.Delete method. However for those who run into this you should be aware that File.Delete DOES NOT throw any exception if it cannot delete the file. It should be good practice to wrap the File.Delete method a check for File.Exists

decrypt pgp files from a folder and moving it - c#

I am trying to decrypt .pgp files from a location and then moving those files to another location. I looked into this article and code accordingly. In my code I am developing an application which will check to a certain location after every 100 seconds and if there are files then it will decrypt and move. but I am getting this exception The process cannot access the file 'c:\file.pgp' because it is being used by another process.
Here is my code where I am calling that class which I copied from that article.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Do the stuff you want to be done every hour;
string sourcePath = #"files location";
string archivePath = #"move original file after decrypting location";
string targetPath = #"decrypted file location";
string pubkeyPath = #"public key location\PGPPublicKey.txt";
string privkeyPath = #"private key location\PGPPrivateKey.txt";
string fileName = "";
string destFile = "";
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
PGPDecrypt test = new PGPDecrypt(s,
privkeyPath,
"password",
targetPath + "decrypted.txt",
pubkeyPath);
FileStream fs = File.Open(s, FileMode.Open);
test.decrypt(fs, targetPath + "decrypted.txt");
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(archivePath, fileName);
System.IO.File.Move(s, archivePath);
}
}
}
Where are you getting the error. If you are getting error while moving it might be because your filestream is not close. After decryption and before move close the filestream with fs.Close();
I believe the issue you are having is caused by the file not being closed, when you loop with the foreach loop the first iteration probably works. However, the next time, because it was never closed, it is still being used.
Try adding
fs.Close();
At the end of the foreach loop
This is I ended up and it is working
//Decrypt
using DidiSoft.Pgp;
PGPLib pgp = new PGPLib();
string inputFileLocation = file Location;
string privateKeyLocation = #"I posted my private at this location";
string privateKeyPassword = "Decryption Password";
string outputFile = #"Output Location";
// decrypt and obtain the original file name
// of the decrypted file
string originalFileName =
pgp.DecryptFile(inputFileLocation,
privateKeyLocation,
privateKeyPassword,
outputFile);
//Move decrypted file to archive
string path = Decrypted file Location;
string path2 = #"Archive file location" + Path.GetFileName(file); ;
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) { }
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
}
catch (Exception e)
{
}

How to copy file from one dir to another under IIS root using asp.net web service?

I am developing asp.net web service using win7 IIs server.under IIs root dir there are two sub dir how can i copy file from one sub folder to another this my try:
string fileName="file.txt";
string sourcePath = #"localhost\C:\inetpub\wwwroot\source";
string targetPath = #"localhost\C:\inetpub\wwwroot\dest";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
thanks in advance
You should use physical paths. That is :
string fileName="file.txt";
string sourcePath = #"C:\inetpub\wwwroot\source";
string targetPath = #"C:\inetpub\wwwroot\dest";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
If you need to involve the website root (in this case, folders on the site root folder), it should be like this:
string fileName="file.txt";
string sourcePath = Server.MapPath("/source");
string targetPath = Server.MapPath("/dest");
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
Best

Move files from one folder to another C# Error File being used by another process

I tired to copy files containing a particular string from one folder to another but it keeps giving me the error message System.IO.IOException: The process cannot access the file 'Z:\Upload\Text-File-1.txt' because it is being used by another process. Have tried a few things but nothing works. Not sure how to fix it.
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
CheckandMoveFiles();
}
private static void CheckandMoveFiles()
{
//put filenames in array
string[] sourcePath = Directory.GetFiles(#"Z:\Upload\");
string targetPath = #"Z:\Upload\TextFiles\";
try
{
//Get each filepath and check for string
foreach (string name in sourcePath)
{
string d = "Text";
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
Console.WriteLine("****************************DONE***************************************");
Console.ReadLine();
}
}
}
It looks like your problem is in the following lines:
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
because fileName already contains the full path, and sourcePath is a string array, so sourcePath.ToString() would not yield the path you expect.
Instead try:
string sourceFile = fileName;
string destFile = System.IO.Path.Combine(targetPath, System.IO.Path.GetFileName(fileName));
using (StreamReader reader = new StreamReader(sourceFile))
{
File.Copy(sourceFile, destFile, true);
}
You're opening a StreamReader to read the sourceFile, and then you try to File.Copy() it? that's why you're getting the error
Lose the StreamReader, you don't need it
File.Copy(sourceFile, destFile, true);
Will do
Should be like this:
if (name.Contains(d))
{
string fileName = name;
string sourceFile = System.IO.Path.Combine(sourcePath.ToString(), fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
File.Copy(sourceFile, destFile, true);
}
File.Copy takes file path as parameter not the stream that points to the file.
Try This Friend...
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}

Categories

Resources