Removing the file with same name, extension doesn't matter - c#

I have some files in "~Content/Documents" folder which holds every uploaded file. In my case the user can only upload one file.
I have done the uploading part where the user can upload his file.
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}
My problem is:
User can upload either ".doc", ".docx", ".xls", ".xlsx", or ".pdf" format files.
Now when the user upload the file of ".doc" format it is uploaded to the folder. Later the same user can upload the file of ".pdf" format which is also uploaded to the folder. That means the user can upload two files.
Now what I want to do is:
When a specific user uploads his document:
->search whether the document uploaded by the user is in that folder or not. i.e. the specific filename with different extension exists or not.
->if the filename already exists with different extension then remove that file and upload the new file.

Try this, Just another way; If your filename is "document"
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
So your code would be;
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
//deleting code starts here
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
//deleting code ends here
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}

Something like this should do the trick
var files = new DirectoryInfo(fullpath).GetFiles();
var filesNoExtensions = files.Select(a => a.Name.Split('.')[0]).ToList();
//for below: or 'document' if that's what you rename it to be on disk
var fileNameNoExtension = fileName.Split('.')[0];
if (filesNoExtensions.Contains(fileNameNoExtension))
{
var deleteMe = files.First(f => f.Name.Split('.')[0] == fileNameNoExtension);
deleteMe.Delete();
}
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));

Get the filename of the new file without extension, then loop through all the filenames in the folder where it will be uploaded to and check if the name already exists. If so, delete the old an upload, else upload.
var info = new FileInfo("C:\\MyDoc.docx");
var filename = info.Name.Replace(info.Extension, "");
var files = Directory.GetFiles("YOUR_DIRECTORY").Select(f => new FileInfo(f).Name);
if (files.Any(file => file.Contains(filename)))
{
//Delete old file
}
//Upload new file

Related

how to save a file in the directory you are currently in (COSMOS)

So I'm making a Cosmos OS and I am having some trouble. I have this code that makes a file. what it does is it asks What is the name of the file and extension then what is the files contents then makes the file. The Problem is is that it only saves to main directory of 0:\ and doesn't work when you make a file while in a directory like 0:\TEST. This is the code I have for the file creator. I want to know if it's possible to make it save the file to the directory you are currently in.
Console.Write("File Name (put in the extension name):");
var finput = Console.ReadLine().ToLower();
string fileName = finput;
// Check if file already exists. If yes, delete it.
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.Write("File Contents:\n");
var text = Console.ReadLine().ToLower();
using (FileStream fs = File.Create(fileName))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes(text);
fs.Write(title, 0, title.Length);
}
Console.WriteLine("File Made!");
This may be a late answer, but try this:
var dir = Directory.GetCurrentDirectory;
var file = (filename);
File.Create(dir + "\\" + file);
I haven't checked this code but it should be something like this. This (should) do the same as your code above.

File.OpenRead() Directories , Sub Directories , Files, and then Write Folders and files to another directory

I am looking to read folders and files from a directory structure like so..
e.g
C:\RootFolder
SubFolder1
SubFolder2
File1
File2
SubFolder3
File3
Files....
Files....
I would like to read both, files and folders and write to another directory I cant use copy , because the directory I want to write to is remote and not local.
I read the files here.... Id love to be able to read folders and files and write both to another directory.
public static IEnumerable<FileInfo> GetFiles(string dir)
{
return Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
.Select(path =>
{
var stream = File.OpenRead(path);
return new FileInfo(Path.GetFileName(path), stream);
})
.DisposeEach(c => c.Content);
}
this function writes files to a remote sftp site.
public Task Write(IEnumerable<FileInfo> files)
{
return Task.Run(() =>
{
using (var sftp = new SftpClient(this.sshInfo))
{
sftp.Connect();
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var file in files)
{
sftp.UploadFile(file.Content, file.RelativePath);
}
}
});
}
In this function I write the read files from the above function.
private async static Task SendBatch(Config config, Batch batch, IRemoteFileWriter writer)
{
var sendingDir = GetClientSendingDirectory(config, batch.ClientName);
Directory.CreateDirectory(Path.GetDirectoryName(sendingDir));
Directory.Move(batch.LocalDirectory, sendingDir);
Directory.CreateDirectory(batch.LocalDirectory);
//Use RemoteFileWriter...
var files = GetFiles(sendingDir);
await writer.Write(files).ContinueWith(t =>
{
if(t.IsCompleted)
{
var zipArchivePath = GetArchiveDirectory(config, batch);
ZipFile.CreateFromDirectory(
sendingDir,
zipArchivePath + " " +
DateTime.Now.ToString("yyyy-MM-dd hh mm ss.Zip")
);
}
});
}
Thank you!
You are getting UnauthorizedAccessException: Access to the path 'C:\temp' is denied. because you can't open a stream from a folder as it doesn't contain bytes.
From what I can understand you are looking to copy the files from one folder to another.
This answer seems to cover what you are doing. https://stackoverflow.com/a/3822913/3634581
Once you have copied the directories you can then create the zip file.
If you don't need to copy the files and just create the Zip I would recommend that since it will reduce the disk IO and speed up the process.
ZipArchive (https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx) can be used to create a zip file straight to a stream.
I figured it out here is the solution
public Task Write(IEnumerable<FileInfo> files)
{
return Task.Run(() =>
{
using (var sftp = new SftpClient(this.sshInfo))
{
sftp.Connect();
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var file in files)
{
var parts = Path.GetDirectoryName(file.RelativePath)
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
sftp.ChangeDirectory(this.remoteDirectory);
foreach (var p in parts)
{
try
{
sftp.ChangeDirectory(p);
}
catch (SftpPathNotFoundException)
{
sftp.CreateDirectory(p);
sftp.ChangeDirectory(p);
}
}
sftp.UploadFile(file.Content, Path.GetFileName(file.RelativePath));
}
}
});
}
****Key point to the solution was
this
var parts = Path.GetDirectoryName(file.RelativePath)
.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
We call *Path.GetDirectoryName
on the file itself to get the directory that correlates to the file.
We split the file directory to get the folder name and finally create the folder name we obtained from the split and upload the file to it.
I hope this helps others who may encounter such issue.

Check for files and creating folders and moving files in C#

I have no problems when I want to create a new folder
I'm working with
Directory.CreateDirectory
Now I'm trying to get all image files from my desktop and I want to move all images to that folder which was created with Directory.CreateDirectory
I've testet file.MoveTo
from here
FileInfo file = new FileInfo(#"C:\Users\User\Desktop\test.txt");
to here
file.MoveTo(#"C:\Users\User\Desktop\folder\test.txt");
This works perfect.
Now I want to do that with all the image files from my dekstop
(Directory.CreateDirectory(#"C:\Users\User\Desktop\Images");)
How could I do that?
Example code of getting images with certain extentions from one root folder:
static void Main(string[] args)
{
// path to desktop
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//get file extentions by speciging the needed extentions
var images = GetFilesByExtensions(new DirectoryInfo(desktopPath) ,".png", ".jpg", ".gif");
// loop thrue the found images and it will copy it to a folder (make sure the folder exists otherwise filenot found exception)
foreach (var image in images)
{
// if you want to move it to another directory without creating a copy use:
image.MoveTo(desktopPath + "\\folder\\" + image.Name);
// if you want to move a copy of the image use this
File.Copy(desktopPath + "\\"+ image.Name, desktopPath + "\\folder\\" + image.Name, true);
}
}
public static IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
var files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Please try this:
You can filter files in a specific directory and then looop through search results to move each file, you might be able to modify search pattern to match on a number of different image file formats
var files = Directory.GetFiles("PathToDirectory", "*.jpg");
foreach (var fileFound in files)
{
//Move your files one by one here
FileInfo file = new FileInfo(fileFound);
file.MoveTo(#"C:\Users\User\Desktop\folder\" + file.Name);
}

read multiple uploaded files in c#

i am develop a project that can save and delete uploaded files from local system. here is the sample code and i am using fileupload asp-control in asp.net c#
List<AttachmentModel> attachmentList = new List<AttachmentModel>();
if (fuAttachment.HasFiles)
{
foreach (HttpPostedFile uploadedFile in fuAttachment.PostedFiles)
{
attachment.AttachmentType = "Attachment";
attachment.FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
uploadedFile.SaveAs(Path.Combine(Server.MapPath(#"~/Attachments/" + uploadedFile)));
attachmentList.Add(attachment);
}
}
objEL.AttachmentList = attachmentList;
i am trying to upload multiple files( >=2 files). but i am able to read only one file that is selected first..
so then i have changed one line
attachment.FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
to
attachment.FileName = uploadedFile.FileName;
but with this i am getting the whole path of the file as
"C:\Users\ThirupathiReddy\Downloads\PSK_logo.jpg"
i just want to read the file name ...
thank you..
Try:
var fullFilename = #"C:\Users\ThirupathiReddy\Downloads\PSK_logo.jpg";
var fileInfo = new FileInfo(fullFilename );
var filename = fileInfo.Name;

c# copying files from source folder to target folder

Source and Target have the same subdirectories like this :
c:\fs\source\a\
c:\fs\source\b\
c:\fs\target\a\
c:\fs\target\b\
I am battling with copying files from source to target if not existing files. What is the best way in C# to compare source folders with target folders - check if target files dont exit, copy files from a specific source (c:\fs\source\a\config.xml and app.config) to a specific target (c:\fs\target\a\). If target files exist, ignore it. How to write it in C#?
Your code example very much appreciated. Thanks!
public void TargetFileCreate()
{
foreach (var folder in SourceFolders)
{
string[] _sourceFileEntries = Directory.GetFiles(folder);
foreach (var fileName in _sourceFileEntries)
{ //dont know how to implement here:
//how to compare source file to target file to check if files exist or not
//c:\fs\source\A\config.xml compares to c:\fs\target\A\ (no files) that should be pasted
//c:\fs\source\B\config.xml compares to c:\fs\target\B\config.xml that is already existed - no paste
}
}
}
foreach (var file in Directory.GetFiles(source))
{
File.Copy(file, Path.Combine(target, Path.GetFileName(file)), false);
}
You can check for each file if it exists this way:
string curFile = #"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
put this inside your loop. then copy those files there.
MSDN CODE:
// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder
// C:\Users\Public\TestFolder\test.txt
// C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// 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);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
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)
{
// 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);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
foreach (var file in Directory.GetFiles(source))
{
var targetFile = System.IO.Path.Combine(target, System.IO.Path.GetFileName(file));
if(!File.Exists(targetFile))
{
File.Copy(file, targetFile)
}
}

Categories