This question already has an answer here:
Compress a file with RAR
(1 answer)
Closed 9 years ago.
In This Method Finally after saving the File Path I have to Copy the same File and i need to move to another place and i need to make that file as a Rar file How to Do this?
public JsonResult UploadResume(HttpPostedFileBase resume)
{
if (resume != null)
{
string Name = System.IO.Path.GetFileName(resume.FileName);
string path = Server.MapPath("~/Uploads/Resume/0");
string extension = Path.GetExtension(resume.FileName);
DirectoryInfo di = null;
if (!Directory.Exists(path))
{
di = Directory.CreateDirectory(path);
}
var filepath = System.IO.Path.Combine(path, 0 + extension);
resume.SaveAs(filepath);
}
return Json(new { result = true }, JsonRequestBehavior.AllowGet);
}
Try like this
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sFileToZip = #"C:\Documents and Settings\My Documents\Visual Studio 2008\Projects\ConsoleApplication1\bin\Debug\Stuff\text1.txt";
string sZipFile = #"C:\Documents and Settings\My Documents\Visual Studio 2008\Projects\ConsoleApplication1\bin\Debug\Stuff\text1.zip";
using (FileStream __fStream = File.Open(sZipFile, FileMode.Create))
{
GZipStream obj = new GZipStream(__fStream, CompressionMode.Compress);
byte[] bt = File.ReadAllBytes(sFileToZip);
obj.Write(bt, 0, bt.Length);
obj.Close();
obj.Dispose();
}
}
}
}
Source
You need to have some kind of third party library that will compress the files into RAR format, or execute a command line tool (like RAR.EXE) to do it.
Get a rar utility (WinRAR, 7-zip or sth else) and start it from your code
System.Diagnostics.ProcessStart(pathToMyUtility, arguments);
and that's it.
Related
I'm doing a tool that is supposed to zip some ".txt" files by the dates of creation.
What I want is to compress in Zip all the txt files created in the same day from a specific folder. I can't find a way to filter the files by the dates.
The File library has a method GetCreationTime which takes the path as a string.
Using this method, you could filter your files.
quick and dirty:
using System.Linq;
using System.IO;
using System.IO.Compression;
public static void GetTxtFiles()
{
var directoryInfo = new DirectoryInfo("pathToFolder");
var specificDay = new DateTime(2022, 06, 15).Date;
var txtFiles = directoryInfo.GetFiles("*.txt")
.Where(x => x.CreationTime.Date.Equals(specificDay))
.ToList();
if (txtFiles.Count == 0)
throw new FileNotFoundException("No txt files have been found");
ArchiveFiles("pathToZip", txtFiles);
}
private static string ArchiveFiles(string zipCreatePath, List<FileInfo> filesToZip)
{
if (File.Exists(zipCreatePath))
File.Delete(zipCreatePath);
using (ZipArchive archive = ZipFile.Open(zipCreatePath, ZipArchiveMode.Create))
{
foreach (var file in filesToZip)
{
archive.CreateEntryFromFile(file.FullName, file.Name);
}
}
return zipCreatePath;
}
For each run, application (windows forms) extracts output to file (excel/.csv/.pdf), creates current date as folder name and stores it locally. Have to capture those output directly to S3 bucket, successfully uploaded each file as below.
AmazonUploader class
using System;
using System.Collections.Generic;
using System.Text;
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
namespace AwsS3DemoConsoleApp
{
public class AmazonUploader
{
public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
SecretConsumer secretConsumer = new SecretConsumer();
IAmazonS3 client = new AmazonS3Client(secretConsumer.AWSAccessKey, secretConsumer.AWSSecretKey, RegionEndpoint.APSouth1);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
{
request.BucketName = bucketName; //no subdirectory just bucket name
}
else
{ // subdirectory and bucket name
request.BucketName = bucketName + #"/" + subDirectoryInBucket;
}
request.Key = fileNameInS3;
request.FilePath = localFilePath;
utility.Upload(request);
return true;
}
}
}
Program class
using System;
namespace AwsS3DemoConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
string fileToBackup = #"C:\Users\marvel\Documents\Spiderman\19-05-2022"; // test file path from the local computer
string myBucketName = "cccfilestorage"; // your s3 bucket name goes here
string s3DirectoryName = "dummy_folder"; // the directory path to a sub folder goes here
string s3FileName = "19-05-2022"; // the name of the file when its saved into the S3 buscket
AmazonUploader myUploader = new AmazonUploader();
myUploader.sendMyFileToS3(fileToBackup, myBucketName, s3DirectoryName, s3FileName);
Console.WriteLine("File uploaded to S3");
}
}
}
I want to upload as a complete directory for each run.
current folder structure
19-05-2022(main directory)
sub directory (1)
sub directory (2)
csv
pdf
excel
I'm sure that we can upload folders using transfer utility
Can anyone please guide me how to achieve it?
I have write a c# code to retrieve all the file names follow by printing one of the information inside. Example File contains (file1.mht, file2.mht, file3.mht). Maybe the contain inside is (aaaaaa, bbbbbb, cccccc) follow the sequence of the file.
Example out output:
file1.mht aaaaaa
file2.mht bbbbbb
file3.mht cccccc
But I encounter the problem it cannot loop the file name follow by showing the content inside. Anyone can helps? Current result is it show all the directory first and only done the work for the first one in directory.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
string str = "";
string mht_text = "";
string directory = "";
string listInfo = "";
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
foreach (char filePath in directory)
{
//Here is my work to retrieve the data in the file
Console.WriteLine("Names:" + str + " " + "Component:" + component);
Console.ReadKey();
}
}
}
}
From your question I understand that you want to print the file name followed by the content of the same, if so you can try:
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
foreach (FileInfo file in Files)
{
// read the content of the file
var content = File.ReadAllText(file.FullName);
// from your question "Example out output: file1.mht aaaaaa"
Console.WriteLine($"{file.Name} {content}");
}
only done the work for the last one in directory.
Yes, that's cause your directory variable is a string string directory = "" which will get overridden by the last value of loop iteration. You rather want to store in a string[] rather if you want to process all of them.
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
Please try this.
foreach (FileInfo file in Files)
{
str = file.Name;
directory += mht_file + str;
Console.WriteLine(directory);
}
I'm creating C# console app to clean up my download folder in windows
my app work fine for video file and move and and delete it from download folder. but how can I make get get the file in subfolder and add it to my files array?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CleanDownloadFolder
{
class Program
{
static void Main(string[] args)
{
string sourcePath = #"C:\Users\___\Downloads";
string targetPath = #"C:\Users\__\Videos";
CopyDirectory(sourcePath, targetPath);
}
private static void CopyDirectory(string sourcePath, string targetPath)
{
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (Path.GetExtension(fileName) == ".avi")
{
System.IO.File.Copy(s, destFile, true);
System.IO.File.Delete(s);
}
}
}
}
}
}
Directory.GetFiles has an overload that could be used to get the list of files in subdirectories
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
The remainder of your code should work as is, however, if your are interested only in the AVI files then you could put that extension directly in the GetFiles call. In that way you get only AVI files and your code could be simplified removing the if
string[] files = Directory.GetFiles(sourcePath. "*.AVI", SearchOption.AllDirectories);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
File.Delete(s);
}
I suggest also to add a using System.IO; at the top of your code file to avoid all of that full namespace typing required without the using
I don't get an error, but the extension isn't changed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string filename;
string[] filePaths = Directory.GetFiles(#"c:\Users\Desktop\test\");
Console.WriteLine("Directory consists of " + filePaths.Length + " files.");
foreach(string myfile in filePaths)
filename = Path.ChangeExtension(myfile, ".txt");
Console.ReadLine();
}
}
}
Path.ChangeExtension only returns a string with the new extension, it doesn't rename the file itself.
You need to use System.IO.File.Move(oldName, newName) to rename the actual file, something like this:
foreach (string myfile in filePaths)
{
filename = Path.ChangeExtension(myfile, ".txt");
System.IO.File.Move(myfile, filename);
}
Ìf you want to change the extension of a file, call File.Move().
This only changes extension of path and not of file.
Reason: Since ChangeExtension is called of Path.ChangeExtension. For file, use System.IO. File Class and its methods.
The documentation for method ChangeExtension says that:
Changes the extension of a path string.
It doesn't say that it changes extension for a file.
I think this is roughly equivalent (correct) code:
DirectoryInfo di = new DirectoryInfo(#"c:\Users\Desktop\test\");
foreach (FileInfo fi in di.GetFiles())
{
fi.MoveTo(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 1) + ".txt"); // "test.bat" 8 - 3 - 1 = 4 "test" + ".txt" = "test.txt"
}
Console.WriteLine("Directory consists of " + di.GetFiles().Length + " files.");
Console.ReadLine();