File copy only x file extension - c#

I have a working method which copies my files, but I want to add a extra function to it.
I want to copy only these file extensions:*.mp4, *.LRV and *.THM.
You can see below that there are 2 methodes and a if.. so there are 3 methodes(did not copy everything of the first methode because it issn't relevant).
Some other guy told me that i need to add:
var extensions = new[] { ".MP4", ".LRV", ".THM" };
var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(new FileInfo(file).Extension));
To the first methode.. but this issn't right i get the next error:"Cannot convert from 'String[]'to'String'"
I think i need to add a loop in the methode: copyall. But i don't know what kind of loop i must make. can someone please help me out with this problem?
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Locatie = dlg.SelectedPath;
var extensions = new[] { ".MP4", ".LRV", ".THM" };
var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(new FileInfo(file).Extension));
Copy1(files1, Locatie + #"\" + "GoPro1");
}
public void Copy1(string sourceDirectory, string targetDirectory){
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
//Gets size of all files present in source folder.
GetSize(diSource, diTarget);
maxbytes = maxbytes / 1024;
progressBar1.Maximum = maxbytes;
CopyAll(diSource, diTarget);
}
public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
total += (int)fi.Length;
copied += (int)fi.Length;
copied /= 1024;
progressBar1.Step = copied;
progressBar1.PerformStep();
label1.Text = (total / 1048576).ToString() + "MB van de " + (maxbytes / 1024).ToString() + "MB gekopieƫrd";
label1.Refresh();
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
MessageBox.Show("Het kopieren is klaar!");
}

var files1 = Directory.GetFiles(GoPro1).Where(file => extensions.Contains(Path.GetExtension(file));
foreach (file in files1)
File.Copy(file, Locatie + #"\" + "GoPro1");
or:
var files1 = New DirectoryInfo(GoPro1).EnumerateFiles.Where(file => extensions.Contains(Path.GetExtension(file));
Copy1(files, Locatie + #"\" + "GoPro1\")
And the Copy method:
public void Copy1(IEnumerble<FileInfo> files, string targetDirectory)
{
maxbytes = files.Sum(x => x.Lenght) / 1024;
progressBar1.Maximum = maxbytes;
foreach(file in files)
{
file.Copy(targetDirectory + file.Name)
... report progress to ProgressBar
}
}

Solved it!
In the last methode: Copyall:
foreach (FileInfo fi in source.GetFiles("*.MP4"))
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
total += (int)fi.Length;
copied += (int)fi.Length;
copied /= 1024;
progressBar1.Step = copied;
progressBar1.PerformStep();
label1.Text = (total / 1048576).ToString() + "MB van de " + (maxbytes / 1024).ToString() + "MB gekopieƫrd";
label1.Refresh();
}

Related

How to create files names according to existing files names?

private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
if (DrawingRects.Count > 0)
{
// The last drawn shape
var dr = DrawingRects.Last();
if (dr.Rect.Width > 0 && dr.Rect.Height > 0)
{
rectImage = cropAtRect((Bitmap)pictureBox2.Image, dr.Rect);
if (saveRectangles)
{
DirectoryInfo dInfo = new DirectoryInfo(#"d:\rectangles");
var files = GetFilesByExtensions(dInfo, ".bmp");
if (files.Count() > 0)
{
foreach (var f in files)
{
}
}
rectangleName = #"d:\Rectangles\rectangle" + saveRectanglesCounter + ".bmp";
FileList.Add($"{dr.Location}, {dr.Size}", rectangleName);
string json = JsonConvert.SerializeObject(
FileList,
Formatting.Indented // this for pretty print
);
using (StreamWriter sw = new StreamWriter(#"d:\rectangles\rectangles.txt", false))
{
sw.Write(json);
sw.Close();
}
rectImage.Save(rectangleName);
saveRectanglesCounter++;
}
pixelsCounter = rect.Width * rect.Height;
pictureBox1.Invalidate();
listBox1.DataSource = FileList.ToList();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
}
I'm using DirectoryInfo and the method GetFilesByExtensions
public IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
if there are existing files for example rectangle1.bmp rectangle2.bmp.....rectangle7.bmp
then when creating a new rectangle file on the hard disk i want it to be rectangle8.bmp
now it's trying to create another rectangle1.bmp and give exception and i don't want to delete the existing files but to create new ones.
and make it as much as possible generic. but the main goal is to create new files names according to those existing and continue the counting.
You can write a method that checks if the proposed name exists or not
string GetNextName(string baseName, string extension)
{
int counter = 1;
string nextName = baseName + counter + extension;
while(File.Exists(nextName))
{
counter++;
nextName = baseName + counter + extension;
}
return nextName;
}
and call it in this way:
rectangleName = GetNextName(#"d:\Rectangles\rectangle", ".bmp");
You can use linq and do everything in one statement like this:
DirectoryInfo di = new DirectoryInfo(#"D:\rectangles");
var maxIndex = di.GetFiles().Select(fi => fi.Name.Replace("rectangle","").Replace(".bmp", "")).Max(i => i);

Downloading a directory using SSH.NET SFTP in C#

I am using Renci.SSH and C# to connect to my Unix server from a Windows machine. My code works as expected when the directory contents are only files, but if the directory contains a folder, I get this
Renci.SshNet.Common.SshException: 'Failure'
This is my code, how can I update this to also download a directory (if exists)
private static void DownloadFile(string arc, string username, string password)
{
string fullpath;
string fp;
var options = new ProgressBarOptions
{
ProgressCharacter = '.',
ProgressBarOnBottom = true
};
using (var sftp = new SftpClient(Host, username, password))
{
sftp.Connect();
fp = RemoteDir + "/" + arc;
if (sftp.Exists(fp))
fullpath = fp;
else
fullpath = SecondaryRemoteDir + d + "/" + arc;
if (sftp.Exists(fullpath))
{
var files = sftp.ListDirectory(fullpath);
foreach (var file in files)
{
if (file.Name.ToLower().Substring(0, 1) != ".")
{
Console.WriteLine("Downloading file from the server...");
Console.WriteLine();
using (var pbar = new ProgressBar(100, "Downloading " + file.Name + "....", options))
{
SftpFileAttributes att = sftp.GetAttributes(fullpath + "/" + file.Name);
var fileSize = att.Size;
var ms = new MemoryStream();
IAsyncResult asyncr = sftp.BeginDownloadFile(fullpath + "/" + file.Name, ms);
SftpDownloadAsyncResult sftpAsyncr = (SftpDownloadAsyncResult)asyncr;
int lastpct = 0;
while (!sftpAsyncr.IsCompleted)
{
int pct = (int)((long)sftpAsyncr.DownloadedBytes / fileSize) * 100;
if (pct > lastpct)
for (int i = 1; i < pct - lastpct; i++)
pbar.Tick();
}
sftp.EndDownloadFile(asyncr);
Console.WriteLine("Writing File to disk...");
Console.WriteLine();
string localFilePath = "C:\" + file.Name;
var fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(fs);
fs.Close();
ms.Close();
}
}
}
}
else
{
Console.WriteLine("The arc " + arc + " does not exist");
Console.WriteLine();
Console.WriteLine("Please press any key to close this window");
Console.ReadKey();
}
}
}
BeginDownloadFile downloads a file. You cannot use it to download a folder. For that you need to download contained files one by one.
The following example uses synchronous download (DownloadFile instead of BeginDownloadFile) for simplicity. After all, you are synchronously waiting for asynchronous download to complete anyway. To implement a progress bar with synchronous download, see Displaying progress of file download in a ProgressBar with SSH.NET.
public static void DownloadDirectory(
SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
{
Directory.CreateDirectory(destLocalPath);
IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
foreach (SftpFile file in files)
{
if ((file.Name != ".") && (file.Name != ".."))
{
string sourceFilePath = sourceRemotePath + "/" + file.Name;
string destFilePath = Path.Combine(destLocalPath, file.Name);
if (file.IsDirectory)
{
DownloadDirectory(sftpClient, sourceFilePath, destFilePath);
}
else
{
using (Stream fileStream = File.Create(destFilePath))
{
sftpClient.DownloadFile(sourceFilePath, fileStream);
}
}
}
}
}

How could i read multiple PDF files from folder in asp.net c#

This is my Upload Button Code. I want to upload pdf file and then read all the files that is uploaded.
protected void Upload_Files(object sender, EventArgs e)
{
if (fileUpload.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
{
int iUploadedCnt = 0;
int iFailedCnt = 0;
HttpFileCollection hfc = Request.Files;
lblFileList.Text = "Select <b>" + hfc.Count + "</b> file(s)";
if (hfc.Count <= 10) // 10 FILES RESTRICTION.
{
for (int i = 0; i <= hfc.Count - 1; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
if (!File.Exists(Server.MapPath("CopyFiles\\") +Path.GetFileName(hpf.FileName)))
{
DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("CopyFiles\\"));
string sFileName = Path.GetFileName(hpf.FileName);
string sFileExt = Path.GetExtension(hpf.FileName);
// CHECK FOR DUPLICATE FILES.
FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + "*.pdf");
if (objFI.Length > 0)
{
// CHECK IF FILE WITH THE SAME NAME EXISTS
foreach (FileInfo file in objFI)
{
string sFileName1 = objFI[0].Name;
string sFileExt1 = Path.GetExtension(objFI[0].Name);
if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
{
iFailedCnt += 1; // NOT ALLOWING DUPLICATE.
break;
}
}
}
else
{
// SAVE THE FILE IN A FOLDER.
hpf.SaveAs(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName));
iUploadedCnt += 1;
}
}
}
}
lblUploadStatus.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
lblFailedStatus.Text = "<b>" + iFailedCnt + "</b> duplicate file(s) could not be uploaded.";
}
else lblUploadStatus.Text = "Max. 10 files allowed.";
}
else lblUploadStatus.Text = "No files selected.";
}
I am facing error in Path.GetExtension(hpf.FileName) in my this method when i m using library using iTextSharp.text.pdf.parser; in my code. i am using Path.GetExtension(hpf.FileName) to upload files from browser.
if (!File.Exists(Server.MapPath("CopyFiles\\") +Path.GetFileName(hpf.FileName)))
{
DirectoryInfo objDir = new DirectoryInfo(Server.MapPath("CopyFiles\\"));
string sFileName = Path.GetFileName(hpf.FileName);
string sFileExt = Path.GetExtension(hpf.FileName);
// CHECK FOR DUPLICATE FILES.
FileInfo[] objFI = objDir.GetFiles(sFileName.Replace(sFileExt, "") + "*.pdf");
if (objFI.Length > 0)
{
// CHECK IF FILE WITH THE SAME NAME EXISTS
foreach (FileInfo file in objFI)
{
string sFileName1 = objFI[0].Name;
string sFileExt1 = Path.GetExtension(objFI[0].Name);
if (sFileName1.Replace(sFileExt1, "") == sFileName.Replace(sFileExt, ""))
{
iFailedCnt += 1; // NOT ALLOWING DUPLICATE.
break;
}
}
}
else
{
// SAVE THE FILE IN A FOLDER.
hpf.SaveAs(Server.MapPath("CopyFiles\\") + Path.GetFileName(hpf.FileName));
iUploadedCnt += 1;
}
}

C# access to TreeNode variable file.CreationTime outside treeView

I need to access to file.CreationTime of selected node in treeView and display it in label outside treeView.
I added .Tag and now in works great when directory is selected, but when file is selected I'm getting that treeView1.SelectedNode.Tag is null and application crashes.
Does anyone have idea how to fix it?
private void ListDirectory(TreeView treeView, string path)
{
treeView1.Nodes.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView1.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" + DirectorySize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)");
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime));
directoryNode.Tag = directoryInfo;
return directoryNode;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (treeView1.SelectedNode.Tag!=null)
{
var directoryInfo = treeView1.SelectedNode.Tag as DirectoryInfo;
var creationTime = directoryInfo.CreationTime.ToString();
label1.Text = creationTime;
var lastAccessTime = directoryInfo.LastAccessTime;
label2.Text = lastAccessTime.ToString();
var lastWriteTime = directoryInfo.LastWriteTime;
label3.Text = lastWriteTime.ToString();
}
else
{
label1.Text = "";
label2.Text = "";
label3.Text = "";
}
}
You are not adding DirectoryInfo after iterating through the files.
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name /*+ " (" + DirectorySize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)"*/);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)" + file.CreationTime));
directoryNode.Tag = directoryInfo;
return directoryNode;
}
Also, you may use FileSystemInfo for Tag, instead of just DirectoryInfo. DirectoryInfo works fine for Directories and Files, however it makes it easy to access the Tag in treeView1_AfterSelected consistently for both Directories and Files if it is FileSystemInfo.
Note that DirectoryInfo and FileInfo are inherited from FileSytemInfo.
You need to add FileInfo to the tree node. Then cast both DirectoryInfo and FileInfo to FileSystemInfo to get creation time, etc.
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
//original code...
// Note: When creating tree node for displaying file,
// assign FileInfo to fileNode.Tag
foreach (var file in directoryInfo.GetFiles()) {
var fileNode = new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime);
fileNode.Tag = file;
directoryNode.Nodes.Add(fileNode);
}
//original code...
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// Note: Both DirectoryInfo and FileInfo, inherrits FileSystemInfo
// thus you can cast both to FileSystemInfo.
var fsInfo = treeView1.SelectedNode.Tag as FileSystemInfo;
if (fsInfo != null)
{
var creationTime = fsInfo.CreationTime.ToString();
label1.Text = creationTime;
var lastAccessTime = fsInfo.LastAccessTime;
label2.Text = lastAccessTime.ToString();
var lastWriteTime = fsInfo.LastWriteTime;
label3.Text = lastWriteTime.ToString();
}
else
{
label1.Text = "";
label2.Text = "";
label3.Text = "";
}
}
Because you don't add any tag to the TreeNode created when you loop over the FileInfo array returned by DirectoryInfo.GetFiles()
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" +
DirectorySize(directoryInfo) +
" bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length +
" files)");
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
{
TreeNode node = new TreeNode(file.Name + " (" + file.Length + " bytes)"+ file.CreationTime);
directoryNode.Nodes.Add(node);
node.Tag = file;
}
directoryNode.Tag = directoryInfo;
return directoryNode;
}

Renaming mulitple files from bottom to top? C#

i have put together this code which renames all the files in a folder in numeric order. What i want to do is make the last image have the name "1", 2nd to last image be named "2" if you catch my drift. im not sure how to do it. i have this so far
try
{
string Path = #"C:\Users\William\Pictures\Documents\Apple iPhone\";
DirectoryInfo di = new DirectoryInfo(Path);
FileInfo[] fiArr = di.GetFiles("*.jpg");
int i = 1;
string path;
foreach (FileInfo fri in fiArr)
{
path = Path + i.ToString() + ".jpg";
fri.MoveTo(path);
i++;
}
}
catch { }
Try this:
try
{
string Path = #"C:\Users\William\Pictures\Documents\Apple iPhone\";
DirectoryInfo di = new DirectoryInfo(Path);
FileInfo[] fiArr = di.GetFiles("*.jpg");
for (var i = fiArr.Length; i > 0; i--)
{
var fri = fiArr[i - 1];
var path = Path + i.ToString() + ".jpg";
fri.MoveTo(path);
}
}
catch { }

Categories

Resources