How to go about searching a server for a specific file? - c#

I am attempting to find a specific file on a web(site/server), and this file could have varying extensions depending upon the server. How would I determine the extension for a unique sever?
Example Possibilities:
website.com/list.bz2
--or--
website.com/list.gz

using System;
using System.IO;
class App
{
public static void Main()
{
string searchPath = #"c:\";
string searchPattern = "list.*";
DirectoryInfo di = new DirectoryInfo(searchPath);
FileInfo[] files = di.GetFiles(searchPattern, SearchOption.AllDirectories);
foreach (FileInfo file in files)
Console.WriteLine(file.FullName);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
If you don't have access to server and want to search it as a anonymous client, then you should search internet for google hacking.

Related

UnRAR DLL unable to be referenced in C#

I was trying to make a program to clean out some directories on my NAS and I noticed that a lot of folders contained nested rar and zip files and I have plenty of space to unpack them. The program should ask the user for a directory to be cleaned then unpack all rars then delete all of the rars. I'm trying to use UnRAR DLL and I cant even get the rars to unpack. I realize I'm having an issue where visual studio 2022 is refusing to recognize the Unrar DLL in the "using" command. Because of that I've been unable to unpack a single file. This is one my first useful programs so if im missing something basic I understand.
This is my initial attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using UnRAR;
namespace Cleaning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Directory To Be Cleaned");
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
string source = rar;
string dest = "C:\\Users\\Kaleb\\OneDrive\\Desktop\Test Area";
UnRAR unrar = new UnRAR();
unrar.Password = "password_of_myarchive";
unrar.Open(#source, UnRAR.OpenMode.Extract);
while (unrar.ReadHeader())
{
unrar.ExtractToDirectory(#dest);
}
unrar.Close();
}
}
}
}
For reference I have added the UnRAR DLL to the project folder.
SO I was able to get it working with the source code from the great people over at SharpCompress and utilizing their source I've got the following stable build.
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Common;
using System;
using System.IO;
using System.Linq;
using System.Globalization;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Enter E to extract all directories in file path");
Console.WriteLine("Enter D to delete all Archives in file path");
Console.WriteLine("REMEMBER TO ALWAYS EXTRACT BEFORE DELETING");
string option = Console.ReadLine();
if (option == "e" || option == "E")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//as a warning this will extract all files from any rar in the slected driectory one at a time in order.
//if a rar is broken it will halt the program until the offendin rar is deleted best way to find is to see what has been extracted so far and go from there
//or one could also limit the directory in order to refine the number of rars to look for
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
var DirectoryFinal = Path.GetDirectoryName(rar);
using (var archive = RarArchive.Open(#rar))
{
foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
{
entry.WriteToDirectory(#DirectoryFinal, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
};
}
}
else if (option == "d" || option == "D")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//be careful with this i would recomend extracting and then chekcing everything first
string rar_path = Console.ReadLine();
string[] TobeDeleted = Directory.GetFiles(rar_path, "*.r*", SearchOption.AllDirectories);
foreach (string rarstobedeleted in TobeDeleted)
{
File.Delete(rarstobedeleted);
}
}
else
{
Console.WriteLine("Thats not an option try again");
}
Console.WriteLine("Cleaning Complete.");
;
}
}
}
}
This work effectively for rar files only for the time being but will effectively clean up any directories where someone may have downloaded a large amount of files stored in separated rars

Recursive Upload to Azure-Files / Create Subfolder

i want to Upload a folder recursivly to an azure-files storage.
The file structure usually has several subfolders.
What is the best way to create the subfolders in azure-files?
foreach (string fullLocalFilename in System.IO.Directory.GetFiles(locationOfFolderToUpload, "*.*", System.IO.SearchOption.AllDirectories))
{
Console.WriteLine(fullLocalFilename);
FileInfo localfile = new FileInfo(fullLocalFilename);
var root = share.GetRootDirectoryReference();
string strPfad = localfile.DirectoryName.Substring(3);
var folder = root.GetDirectoryReference(strPfad);
Console.WriteLine(strPfad);
folder.CreateIfNotExists();
CloudFile file = folder.GetFileReference(localfile.Name);
if (file.Exists() == false) {
file.Create(localfile.Length);
file.UploadFromFile(fullLocalFilename);
Console.WriteLine(fullLocalFilename);
}
}
WebException: The remote server returned an error: (404) Not found.
I suggest you make use of Microsoft.Azure.Storage.DataMovement, it supports uploading directory to azure as well create the same structure like in local path. Please install the latest version 1.0.0 of Microsoft.Azure.Storage.DataMovement here. Note that if you have installed other azure storage sdk, please uninstall them first.
For example, if I have a local folder like below:
Use the code below:
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.DataMovement;
using Microsoft.Azure.Storage.File;
namespace AzureDataMovementTest
{
class Program
{
static void Main(string[] args)
{
string storageConnectionString = "xxxx";
CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
CloudFileClient fileClient = account.CreateCloudFileClient();
CloudFileShare fileShare = fileClient.GetShareReference("t22");
fileShare.CreateIfNotExists();
CloudFileDirectory fileDirectory= fileShare.GetRootDirectoryReference();
//here, I want to upload all the files and subfolders in the follow path.
string source_path = #"F:\temp\1";
//if I want to upload the folder 1, then use the following code to create a file directory in azure.
CloudFileDirectory fileDirectory_2 = fileDirectory.GetDirectoryReference("1");
fileDirectory_2.CreateIfNotExists();
UploadDirectoryOptions directoryOptions = new UploadDirectoryOptions
{
Recursive = true
};
var task = TransferManager.UploadDirectoryAsync(source_path,fileDirectory_2,directoryOptions,null);
task.Wait();
Console.WriteLine("the upload is completed");
Console.ReadLine();
}
}
}
After the code completes running, nav to azure portal -> file storage:
Please let me know if you have more issues.

C# load folder names

I would like my program to read sub-folders from folder in my solution, but i don't know how to read folder names. I can only find, how to read file names and this is not hard to get to work, but with folders, this doesn't seem to work the same way.
Basically I want to load from "Paevik" (2) sub-folders.
E: I forgot to mention, that I want that list into my comboBox
There is System.IO.Directory.EnumerateDirectories(string Path)-method. It returns a collections with directories. Example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
private static void Main(string[] args)
{
try
{
string dirPath = #"\\archives\2009\reports";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
foreach (var dir in dirs)
{
Console.WriteLine("{0}", dir.Substring(dir.LastIndexOf("\\") + 1));
}
Console.WriteLine("{0} directories found.", dirs.Count);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
See MSDN.
Try DirectoryInfo.EnumerateDirectories Method
http://msdn.microsoft.com/en-us/library/dd413235.aspx
You can use "GetDirectories" to retrieve an array containing full names of all subdirectories.
string[] subdirectories = Directory.GetDirectories("Full path of your parent folder");
See sample on MSDN page.

How can I add more directories to my file deletion program?

I'm trying to use this to delete all .htm files in certain in a couple of directories I have by using recursion. So far it works fine with just one folder, but I haven't been able to find a way to add more than one folder to the code. Is there any way i can add more directories to the directory path so I don't have to keep changing the code every time I want it to delete files in another directory?
namespace ConsoleApplication
{
class Deleter
{
static void Main(string[] args)
{
string directorypath = #"C:\Public\";
string[] directories = System.IO.Directory.GetDirectories(directorypath);
DeleteDirectories(directories);
}
private static void DeleteDirectories(string[] directories)
{
foreach (string directory in directories)
{
string[] files = System.IO.Directory.GetFiles(directory, "*.htm");
DeleteFiles(files);
directories = System.IO.Directory.GetDirectories(directory);
DeleteDirectories(directories);
}
}
private static void DeleteFiles(string[] files)
{
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
if (f.CreationTime < DateTime.Now)
f.Delete();
}
}
}
}
Rather than setting your enumerable (directories) to the sub directories & hoping to recurse that way, create a new reference named subDirectories. So your foreach loop will look like this:
...
foreach(var directory in directories)
{
string[] files = System.IO.Directory.GetFiles(directory, "*.htm");
DeleteFiles(files);
var subDirectories = System.IO.Directory.GetDirectories(directory);
DeleteDirectories(directories);
{
....

What is the best way to empty a directory?

Is there a way to delete all files & sub-directories of a specified directory without iterating over them?
The non elegant solution:
public static void EmptyDirectory(string path)
{
if (Directory.Exists(path))
{
// Delete all files
foreach (var file in Directory.GetFiles(path))
{
File.Delete(file);
}
// Delete all folders
foreach (var directory in Directory.GetDirectories(path))
{
Directory.Delete(directory, true);
}
}
}
How about System.IO.Directory.Delete? It has a recursion option, you're even using it. Reviewing your code it looks like you're trying to do something slightly different -- empty the directory without deleting it, right? Well, you could delete it and re-create it :)
In any case, you (or some method you use) must iterate over all of the files and subdirectories. However, you can iterate over both files and directories at the same time, using GetFileSystemInfos:
foreach(System.IO.FileSystemInfo fsi in
new System.IO.DirectoryInfo(path).GetFileSystemInfos())
{
if (fsi is System.IO.DirectoryInfo)
((System.IO.DirectoryInfo)fsi).Delete(true);
else
fsi.Delete();
}
Why is that not elegant? It's clean, very readable and does the job.
Well, you could always just use Directory.Delete....
http://msdn.microsoft.com/en-us/library/aa328748%28VS.71%29.aspx
Or if you want to get fancy, use WMI to delete the directory.
Here's an extension method based on the OPs original code, which I think is just fine and a bit more readable than other options.
I agree it would be nice to have a single method in the framework to delete the contents of a directory without deleting the directory, but in my opinion, this is the next best thing.
using System;
using System.IO;
namespace YourNamespace
{
public static class DirectoryInfoExtensions
{
public static void EmptyDirectory(this DirectoryInfo di)
{
if (di.Exists)
{
foreach (var file in di.GetFiles())
{
file.Delete();
}
foreach (var directory in di.GetDirectories())
{
directory.Delete(true);
}
}
}
}
}

Categories

Resources