Saving multiple images using File.WriteAllBytes saves only the last one - c#

i'm trying to save multiple images with File.WriteAllBytes(), even after i tried to seperate between the saves with 'Thread.Sleep()' it's not working..
my code:
byte[] signatureBytes = Convert.FromBase64String(model.Signature);
byte[] idBytes = Convert.FromBase64String(model.IdCapture);
//Saving the images as PNG extension.
FileManager.SaveFile(signatureBytes, dirName, directoryPath, signatureFileName);
FileManager.SaveFile(idBytes, dirName, directoryPath, captureFileName);
SaveFile Function:
public static void SaveFile(byte[] imageBytes, string dirName, string path, string fileName, string fileExt = "jpg")
{
if (!string.IsNullOrEmpty(dirName)
&& !string.IsNullOrEmpty(path)
&& !string.IsNullOrEmpty(fileName)
&& imageBytes.Length > 0)
{
var dirPath = Path.Combine(path, dirName);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
File.WriteAllBytes(dirPath + $#"\{fileName}.{fileExt}", imageBytes);
}
}
else
throw new Exception("File cannot be created, one of the parameters are null or empty.");
}

File.WriteAllBytes():
"Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten"
As expecify in :
https://msdn.microsoft.com/en-ca/library/system.io.file.writeallbytes(v=vs.110).aspx
So if you can only see the last one, you are overwriting the file.

Apart from the possibility (as mentioned by #Daniel) that you're overwriting the same file, I'm not sure about this code:
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
...
}
I'd be surprised if, having called di.Create(), the Exists property is updated. In fact, it is not updated - I checked.
So, if the directory did not exist, then you won't enter the conditional part even after creating the directory. Could that explain your issue?

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.

Storing and getting back files from MongoDB

I am working on c# .Net 4.5
I have to upload some files on MongoDB and in other module, I have to get them back based on metadata.
for that I am doing like below,
static void uploadFileToMongoDB(GridFSBucket gridFsBucket)
{
if (Directory.Exists(_sourceFilePath))
{
if (!Directory.Exists(_uploadedFilePath))
Directory.CreateDirectory(_uploadedFilePath);
FileInfo[] sourceFileInfo = new DirectoryInfo(_sourceFilePath).GetFiles();
foreach (FileInfo fileInfo in sourceFileInfo)
{
string filePath = fileInfo.FullName;
string remoteFileName = fileInfo.Name;
string extension = Path.GetExtension(filePath);
double fileCreationDate = fileInfo.CreationTime.ToOADate();
GridFSUploadOptions gridUploadOption = new GridFSUploadOptions
{
Metadata = new BsonDocument
{{ "creationDate", fileCreationDate },
{ "extension", extension }}
};
using (Stream fileStream = File.OpenRead(filePath))
gridFsBucket.UploadFromStream(remoteFileName, fileStream, gridUploadOption);
}
}
}
and downloading,
static void getFileInfoFromMongoDB(GridFSBucket bucket, DateTime startDate, DateTime endDate)
{
double startDateDoube = startDate.ToOADate();
double endDateDouble = endDate.ToOADate();
var filter = Builders<GridFSFileInfo>.Filter.And(
Builders<GridFSFileInfo>.Filter.Gt(x => x.Metadata["creationDate"], startDateDoube),
Builders<GridFSFileInfo>.Filter.Lt(x => x.Metadata["creationDate"], endDateDouble));
IAsyncCursor<GridFSFileInfo> fileInfoList = bucket.Find(filter); //****
if (!Directory.Exists(_destFilePath))
Directory.CreateDirectory(_destFilePath);
foreach (GridFSFileInfo fileInfo in fileInfoList.ToList())
{
string destFile = _destFilePath + "\\" + fileInfo.Filename;
var fileContent = bucket.DownloadAsBytes(fileInfo.Id); //****
File.WriteAllBytes(destFile, fileContent);
}
}
in this code (working but) I have two problems which I am not sure how to fix.
If i have uploaded a file and I upload it again, it actually gets
uploaded. How to prevent it?
Ofcourse both uploaded files have different ObjectId but while uploading a file I will not be knowing that which files are already uploaded. So I want a mechanism which throws an exception if i upload already uploaded file. Is it possible? (I can use combination of filename, created date, etc)
If you have noticed in code, actually i am requesting to database server twice to get one file written on disk, How to do it in one shot?
Note lines of code which I have marked with "//****" comment. First I am querying into database to get fileInfo (GridFSFileInfo). I was expecting that I could get actual content of file from this objects only. But I didnot find any related property or method in that object. so I had to do var fileContent = bucket.DownloadAsBytes(fileInfo.Id); to get content. M I missing something basic here ?

Directory Not Found Exception C#

I am creating the file list of both source & target directory in target location, the requirement is based on the difference of these two files copy only the files that are new from last iteration.
For 1st iteration copy works, next iteration creates a blank diff [Difference] file is created, to handle this I have added if condition where I check length of file and copy them again. But the if condition is not working as per behavior, with length zero it goes to else statement and throws out error with blank file name :
Could not find a part of the path 'C:\interswitch\source\'.
Here's the code:
string path = Path.Combine(target_dir, "Diff.txt");
if (new FileInfo(path).Length == 0)
{
foreach (FileInfo fi in sourceinfo.GetFiles())
{
fi.CopyTo(Path.Combine(targetinfo.ToString(), fi.Name), true);
}
}
else
foreach (string file in File.ReadLines(path))
{
{
string sourceFile = System.IO.Path.Combine(source_dir, file);
string destFile = System.IO.Path.Combine(target_dir, file);
System.IO.File.Copy(sourceFile, destFile, true);
}
}
if (new FileInfo(path).Length == 0)
does not produce 0 apparently, you have to fix that

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

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

Copy file to a different directory

I am working on a project where I want to copy some files in one directory to a second already existing directory.
I can't find a way to simply copy from one folder to another. I can find copy file to a new file, or directory to a new directory.
The way I have my program set up right now is I copy the file and leave it in same directory, then move that copy to the directory that I want.
Edit:
Thanks everyone. All of your answers worked. I realized what I did wrong, when i set the destination path I didn't add a filename. Everything works now, Thanks for the super speedy responses.
string fileToCopy = "c:\\myFolder\\myFile.txt";
string destinationDirectory = "c:\\myDestinationFolder\\";
File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));
File.Copy(#"someDirectory\someFile.txt", #"otherDirectory\someFile.txt");
works fine.
MSDN File.Copy
var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);
File.Copy(source, destination);
Maybe
File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");
?
This worked for me:
string picturesFile = #"D:\pictures";
string destFile = #"C:\Temp\tempFolder\";
string[] files = Directory.GetFiles(picturesFile);
foreach (var item in files)
{
File.Copy(item, destFile + Path.GetFileName(item));
}
I used this code and it work for me
//I declare first my variables
string sourcePath = #"Z:\SourceLocation";
string targetPath = #"Z:\TargetLocation";
string destFile = Path.Combine(targetPath, fileName);
string sourceFile = Path.Combine(sourcePath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
If the destination directory doesn't exist, File.Copy will throw. This version solves that
public void Copy(
string sourceFilePath,
string destinationFilePath,
string destinationFileName = null)
{
if (string.IsNullOrWhiteSpace(sourceFilePath))
throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
if (string.IsNullOrWhiteSpace(destinationFilePath))
throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);
//this creates all the sub directories too
if (!targetDirectoryInfo.Exists)
targetDirectoryInfo.Create();
var fileName = string.IsNullOrWhiteSpace(destinationFileName)
? Path.GetFileName(sourceFilePath)
: destinationFileName;
File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
}
Tested on .NET Core 2.1
NET6 - Extension method
[DebuggerStepThrough]
public static FileInfo CopyToDir(this FileInfo srcFile, string destDir) =>
(srcFile == null || !srcFile.Exists) ? throw new ArgumentException($"The specified source file [{srcFile.FullName}] does not exist", nameof(srcFile)) :
(destDir == null || !Directory.Exists(destDir)) ? throw new ArgumentException($"The specified destination directory [{destDir}] does not exist", nameof(destDir)) :
srcFile.CopyTo(Path.Combine(destDir, srcFile.Name), true);

Categories