Copy file code? - c#

I need a copy file on folder to another folder and i'm use this
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
folderBrowserDialog1.ShowDialog();
string xx = folderBrowserDialog1.SelectedPath;
folderBrowserDialog1.ShowDialog();
string yy = folderBrowserDialog1.SelectedPath;
File.Copy(xx, yy);
But is not working.
Why?

Try this code.
I assume you want to read a file then write it to new one.
Hope it helps.
string sourceFile;
string newFile = "C:\NewFile\NewFile.txt";
string fileToRead = "C:\ReadFile\ReadFile.txt";
bool overwriteExistingFile = true; //change to false if you want no to overwrite the existing file.
bool isReadSuccess = getDataFromFile(fileToRead, ref sourceFile);
if (isReadSuccess)
{
File.Copy(sourceFile, newFile, overwriteExistingFile);
}
else
{
Console.WriteLine("An error occured :" + sourceFile);
}
//Reader Method you can use this or modify it depending on your needs.
public static bool getDataFromFile(string FileToRead, ref string readMessage)
{
try
{
readMessage = "";
if (!File.Exists(FileToRead))
{
readMessage = "File not found: " + FileToRead;
return false;
}
using (StreamReader r = new StreamReader(FileToRead))
{
readMessage = r.ReadToEnd();
}
return true;
}
catch (Exception ex)
{
readMessage = ex.Message;
return false;
}
}

It seems that you do not use filenames in your source code.
I made an example. File copy function.
public void SaveStockInfoToAnotherFile(string sPath, string dPath, string filename)
{
string sourcePath = sPath;
string destinationPath = dPath;
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destinationFile = System.IO.Path.Combine(destinationPath, filename);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}

//folderBrowserDialog1.ShowDialog();
//string xx = folderBrowserDialog1.SelectedPath;
//string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//folderBrowserDialog1.ShowDialog();
//string yy = folderBrowserDialog1.SelectedPath;
//foreach (string file in files)
//{
// File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file));

Related

An item with the same key has already been added Ionic.Zip

Good afternoon, please tell me how can I add files with the same name to the archive? To be like copying, the file becomes file(1).* and there are two files file and file(1) . I am using Ionic.Zip
string BackupDir = #"C:\Users\Desktop\dir\backup.zip";
string PathToFolder = #"C:\Users\Desktop\dir";
string[] AllFiles = Directory.GetFiles(PathToFolder, "*.*", SearchOption.AllDirectories);
using (ZipFile zip = new ZipFile(BackupDir, Encoding.UTF8))
{
foreach (string file in AllFiles)
{
try
{
DateTime FileCreationTime = File.GetCreationTime(file);
if (FileCreationTime >= DateTime.Now - new TimeSpan(60, 0, 0, 0))
{
Console.WriteLine(file);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
zip.AddFile(file, "");
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
zip.Save(BackupDir);
}
}
Try this:
//keep track of fileNames
var fileNames = new HashSet<string>(StringCompaer.OridialIgnoreCase);
foreach (string file in AllFiles)
{
try
{
DateTime FileCreationTime = File.GetCreationTime(file);
if (FileCreationTime >= DateTime.Now - new TimeSpan(60, 0, 0, 0))
{
Console.WriteLine(file);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
var fileName = Path.GetFileName(file);
if (fileNames.Add(fileName))
zip.AddFile(file, ""); //fileName could be added to fileNames = it is unique
else
{
//start with 1
int counter = 1;
//loop till you found a fileName thats not occupied
while (true)
{
//build the new file name
var newFileName = $"{Path.GetFileNameWithoutExtension(fileName)} - {counter}{Path.GetExtension(fileName}";
if (fileNames.Add(newFileName))
{
fileName = newFileName; //use the new fileName
break; //break the loop
}
//increase counter if newFileName is already in the list fileNames
counter++;
}
var zipFileEntry = zip.AddFile(file, "");
zipFileEntry.FileName = fileName;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
zip.Save(BackupDir);
}
Check if file exists and add suffix to it's name.
Something like (Pseudocode):
int nameCount = 1;
fileName = file.Name;
while(fileName exists in archive)
{
nameCount++;
fileName = file.Name + "_" + nameCount;
}

Convert Password Protected Zip file to Enc File using c#

I have used the following below code to convert the zip file to enc file but its not working perfectly, please help me to solve this issue
Also if there is any third party tool to convert the zip to enc file please mention the details about it .
Thanks in Advance
try
{
string startPath = "";
string path = #"F:\Augustin\UpTest\Upload\";
DirectoryInfo objdirinfovikramfile = new DirectoryInfo(path);
if (objdirinfovikramfile.Exists)
{
errorcheck = "a";
foreach (DirectoryInfo objdirenmvikramfile in objdirinfovikramfile.GetDirectories())
{
string checkvikramfile = "";
checkvikramfile = objdirenmvikramfile.Name;
startPath = path + checkvikramfile + "\\";
string zipPath = path + checkvikramfile + ".zip";
string sub = zipPath.Split('\\').Last();
Boolean decrypt = false;
FileManager obj = new FileManager();
Int64 secure_count = 0;
while (secure_count <= 3 && !decrypt)
{
decrypt = obj_viki1.Decryption(zipPath, zipPath.Replace(".zip", ".enc"), "dietcoke1"); //DLL Function
secure_count++;
}
if (secure_count > 3 && !decrypt)
{
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(),true );
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(), true);
}
else
{
File.Copy(zipPath, path + "\\SUCCESS\\" + zipPath.Split('\\').Last(), true);
}
}
}
}
catch (Exception ex)
{
Error_log("FileProcess Enc: " + errorcheck + " ", ex.ToString());
Application.Exit();
}

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

Copying files within C# issue

I am creating a project to do with some simple tasks to help my work.
The application is being made as a windows form in C#.
Everything seems to be fine other than one issue, the issue is that when copying files from a shared location to a local location, all of them work other than one.
the code is as follows:
private void Form1_Load_1(object sender, EventArgs e)
{
string fileName = "Analyst's Name.txt";
string fileName1 = "Group Name.txt";
string fileName2 = "KB Number.txt";
string fileName3 = "Return Notes.txt";
string sourcePath = #"\\remote location";
string targetPath = #"C:\SUPPORT\";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string sourceFile1 = System.IO.Path.Combine(sourcePath, fileName1);
string sourceFile2 = System.IO.Path.Combine(sourcePath, fileName2);
string sourceFile3 = System.IO.Path.Combine(sourcePath, fileName3);
string destFile = System.IO.Path.Combine(targetPath, fileName);
string destFile1 = System.IO.Path.Combine(targetPath, fileName1);
string destFile2 = System.IO.Path.Combine(targetPath, fileName2);
string destFile3 = System.IO.Path.Combine(targetPath, fileName3);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Copy(sourceFile, destFile, true);
System.IO.File.Copy(sourceFile1, destFile1, true);
System.IO.File.Copy(sourceFile2, destFile2, true);
System.IO.File.Copy(sourceFile3, destFile3, 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);
destFile1 = System.IO.Path.Combine(targetPath, fileName1);
destFile2 = System.IO.Path.Combine(targetPath, fileName2);
destFile3 = System.IO.Path.Combine(targetPath, fileName3);
System.IO.File.Copy(s, destFile, true);
System.IO.File.Copy(s, destFile1, true);
System.IO.File.Copy(s, destFile2, true);
System.IO.File.Copy(s, destFile3, true);
now the problem is that the return notes file that is locally on the C drive, is being copied but the data within it is showing as the analyst name data, the name of the file is correct, but the data inside is from a different file, any help would be appreciated.
It should be as simple as this:
List<string> files = new List<string>
{
"Analyst's Name.txt",
"Group Name.txt",
"KB Number.txt",
"Return Notes.txt"
};
string sourcePath = #"\\remote location";
string targetPath = #"C:\SUPPORT\";
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
for (int i = 0; i < files.Count; i++)
{
string filePath = Path.Combine(sourcePath, files[i]);
if (File.Exists(filePath))
{
File.Copy(filePath, Path.Combine(targetPath, files[i]), true);
}
}

SSIS script to remove date from file name

I need to create a SSIS script to remove the date from file name. for example file name is: TestFile_122413.CSV I need to rename it to TestFile.CSV. I don't know how to keep file extension and how to deal with the date changes on file. I receive this file every day. Here is my code:
`public void Main()
// TODO: Add your code here
const string DIRECTORY_PATH = #"E:\ScriptsTest";
//const string FILE_NAME_TEMPLATE = "SSS_PROF_010113.CSV";
const string FILE_NAME_TEMPLATE = "*.CSV";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
File.Move(filePath, filePath.Replace(FILE_NAME_TEMPLATE, FILE_NAME_TEMPLATE.Substring(0,8)));
}
}
}
}`
This should work. BTW, have you tried using the ForEach task? That may be simpler.
public void Main()
{
const string DIRECTORY_PATH = #"C:\temp\";
const string FILE_NAME_TEMPLATE = "*_??????.CSV";
int underscoreAt = 0;
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH,FILE_NAME_TEMPLATE);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
underscoreAt = filePath.LastIndexOf('_');
string newName = string.Format ("{0}.CSV", filePath.Substring(0, underscoreAt));
File.Move(filePath,newName );
}
}
}
}
Check out the SSIS File System Task. It has an operation to rename a file.
Here is a video on how it works.
Hope this helps!
Eric
Try this, it compiles but I haven't run it:
public class Foo
{
public void Main()
{
const string DIRECTORY_PATH = #"E:\ScriptsTest";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
// Get the file name
string fileName = Path.GetFileName(filePath);
// Get the file extension
string fileExtension = Path.GetExtension(filePath);
// Get the file name without the date part
string fileTitle = fileName.Substring(0, fileName.IndexOf("_"));
File.Move(filePath, DIRECTORY_PATH + #"\" + fileTitle + "." + fileExtension);
}
}
}
}
}

Categories