Store file temporary [duplicate] - c#

This question already has answers here:
Where can I write a temp file from ASP.NET?
(1 answer)
How to get temporary folder for current user
(3 answers)
Closed 8 years ago.
I have this code for my drag&drop-function for images. The problem with it is that it saves the file to my computer #"C:\Users\xxxx\Desktop\ temporarily. This is a problem because it means that a user cant use this function. So how can i adjust my code in order to make it work online?
I somehow need to find a way that stores the image temporarily.
public ActionResult SaveUploadedFile(string test)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
var filename = Path.GetFileName(file.FileName);
var sourceimage = System.Drawing.Image.FromStream(file.InputStream);
img = sourceimage;
var dog = new Dog();
byte[] tempImg = dog.imageToByteArray(sourceimage);
var fullPath = #"C:\Users\xxxx\Desktop\" + filename;
file.SaveAs(fullPath);
string link = dog.UploadImage(fullPath);
JObject o = JObject.Parse(link);
string name = (string) o.SelectToken("data.link");
System.IO.File.Delete(#"C:\Users\xxxx\Desktop\" + filename);
var page = RavenSession.Load<DogContentPage>(test);
page.Image = name;
RavenSession.SaveChanges();
}
The method that uploads img to imahehost(dunno if it is relevant):
public string UploadImage(string xOut)
{
using (var w = new WebClient())
{
var values = new NameValueCollection
{
{"image", Convert.ToBase64String(File.ReadAllBytes(xOut))}
};
w.Headers.Add("Authorization", "Client-ID " + ClientId);
var response = w.UploadValues("https://api.imgur.com/3/image", values);
var sr = new StreamReader(new MemoryStream(response));
string result = sr.ReadLine();
return result;
}

Have a look at Path.GetTempPath() as well as Path.GetTempFileName() which can help you.
A quick solution would be:
// var fullPath = #"C:\Users\xxxx\Desktop\" + filename; // Not good, since user folder
var fullPath = Path.GetTempFileName(); // Temp file, with unqiue name
The reason I would recommend Path.GetTempFileName() rather than Path.GetTempPath() + filename is that the filename doesn't matter when you only upload the file-bytes, and it guarantees a unique filename so it is impossible to have filename clashes.
var fullPath = Path.GetTempPath() + filename; // No good, could clash if the filenames were the same

Rather than using a hard-coded string, you should use the following to find the temporary folder in which to store temporary files:
string tempPath = System.IO.Path.GetTempPath();

2 solutions I think:
N°1: a task in the server that check, let's say 2 times a day, if any file have to be deleted
N°2: a procedure called by your application to verify the difference between Now and the expiration date of your file.
Hope this ideas can help.

Related

Append timestamp to csv file in c#

I am trying to generate unique csv files by appending timestamps at the end of the file name.
But for some reason csv file is not generating.
String path= #"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\data.csv";
FileInfo info = new FileInfo(path);
bool exists = info.Exists;
library.WriteErrorLog(exists.ToString());
// Upload data from file
--> string result = "data_" + DateTime.Now.ToFileTime() + ".csv";
if(exists == true)
{
File.Delete(Path.GetFileName(path));
sqlRun();
File.WriteAllText(#"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\**result**", csv.ToString());
}
else
{
sqlRun();
File.WriteAllText(#"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\**result**", csv.ToString());
}
}
I think you have forgotten to combine the folder path and the expected filename
Here goes your code refactored (not tested):
var folder = #"C:\\Users\Isuruh\source\repos\WindowsService1\WindowsService1\bin\Debug\";
var path = Path.Combine(folder, "data.csv");
FileInfo info = new FileInfo(path);
bool exists = info.Exists;
library.WriteErrorLog(exists.ToString());
// Upload data from file
var result = "data_" + DateTime.Now.ToFileTime() + ".csv";
var fullResultPath = Path.Combine(folder, result);
if(exists)
{
// Do you really want to delete the data.csv file ?
File.Delete(path);
}
sqlRun();
File.WriteAllText(fullResultPath, csv.ToString());

Access File system Azure App Service

I have an Azure App (.Net 4.5) and I have some static files stored on the filesystem that I want to read from, but I get a System.UnauthorizedAccessException like so
string template = string.Empty;
var file = HostingEnvironment.MapPath("~/App_Data/EmailTemplates/" + fileName);
if (!string.IsNullOrEmpty(file))
{
template = File.ReadAllText(file); <-- Unauthorized Access Exception Here
}
return template;
I know the best practice is Azure Storage, but how do I make this work this way?
As File.ReadAllText states about UnauthorizedAccessException, it could be caused by one of the following conditions:
path specified a file that is read-only.
-or-
This operation is not supported on the current platform.
-or-
path specified a directory.
-or-
The caller does not have the required permission.
You could leverage kudu console and use Attrib command to check the attributes for your files or directories. Also, you could try to use TYPE command to display the contents of your file or click the Edit button from the file list table as follows:
Also, I created a new web app and deployed my MVC application for displaying the files under the App_Data folder, it could work as expected, you could refer to it.
UPDATE:
//method for getting files
public List<DownLoadFileInformation> GetFiles()
{
List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data"));
int i = 0;
foreach (var item in dirInfo.GetFiles())
{
lstFiles.Add(new DownLoadFileInformation()
{
FileId = i + 1,
FileName = item.Name,
FilePath = dirInfo.FullName + #"\" + item.Name
});
i = i + 1;
}
return lstFiles;
}
//action for downloading a file
public ActionResult Download(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string contentType = MimeMapping.GetMimeMapping(fullFilePath);
return File(fullFilePath, contentType, new FileInfo(fullFilePath).Name);
}
UPDATE2:
public ActionResult ViewOnline(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string text = System.IO.File.ReadAllText(fullFilePath);
return Content(text);
}

How to replace an image with same name but different type of another image in a folder?

Suppose i have a folder and in this folder is an image named im1.png. i want that im1.png is deleted when i save another image named im1.jpg or im1.bmp or so on...(same name but different type) in this folder. i write following code but this code just delete file that has same name and same type. Help me please...
string CopyPic(string MySourcePath, string key, string imgNum)
{
string curpath;
string newpath;
curpath = Application.Current + #"\FaceDBIMG\" + key;
if (Directory.Exists(curpath) == false)
Directory.CreateDirectory(curpath);
newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));
string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();
foreach (var similarFile in similarFiles)
File.Delete(similarFile);
File.Copy(MySourcePath, newpath);
return newpath;
}
Here is one way to do it:
string filename = ...; //e.g. c:\directory\filename.ext
//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);
//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
Directory.GetFiles(dir, filenameWithoutExtension + ".*")
.Except(
new []{filename},
//We should ignore the case when we remove the file itself
StringComparer.OrdinalIgnoreCase)
.ToArray();
//Delete these files
foreach(var similarFile in similarFiles)
File.Delete(similarFile);

File.Copy in C# NOT Working

After using the File.Copy function to copy a text file from one location to another i try the exact same functionality (that i've already gotten to work) on another text file fails to write. However, the weird part is that there is NO EXCEPTION thrown! I know the file exists by doing
if(File.Exist(myFile))
My File.Copy code:
File.Copy(sourceFilePathCombined, targetFilePathCombined, true);
This works well for one file in the same directory, but not for the other. There is NO exception. Why won't it write the file, but the other file gets copied without issue?
Code for those who need it:
var indexFileDirectory = ConfigurationManager.AppSettings["Accident.IndexFileDirectory"];
var xRefToDoList = ConfigurationManager.AppSettings["Accident.XRefToDoList"];
var xRefToDoResult = ConfigurationManager.AppSettings["Accident.XRefToDoResult"];
var toDoFilePath = Path.Combine(indexFileDirectory, xRefToDoResult);
var indexFilePath = Path.Combine(indexFileDirectory , xRefToDoList);
//Includes date-time stamp to suffix the file
var xRefToDoResultsDateTime = DateTime.Now.ToString("yyMMddhhmmss");
//If the directory does not exist then create it
if (!Directory.Exists(XRefPath))
{
Directory.CreateDirectory(XRefPath);
}
var indexToStart = xRefToDoList.IndexOf(".");
var test2 = xRefToDoList.Remove(indexToStart, 4);
indexToStart = xRefToDoResult.IndexOf(".");
var test3 = xRefToDoResult.Remove(indexToStart, 8);
var xRefToDoListCombinedPath = Path.Combine(XRefPath, (test2 + "_lst" + "." + xRefToDoResultsDateTime));
var xRefResultListCombinedPath = Path.Combine(XRefPath, (test3 + "_results" + "." + xRefToDoResultsDateTime));
string extension = Path.GetExtension(toDoFilePath);
try
{
File.Copy(indexFilePath, xRefToDoListCombinedPath, true);//THIS WORKS!
File.Copy(toDoFilePath, xRefResultListCombinedPath, true);//this does NOT
}
catch (Exception ex)
{
var test = ex;
}
Try using foreach to move all files
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
string[] files = Directory.GetFiles(sourcePath);
foreach (var file in files)
{
string name = Path.GetFileName(file);
string target = Path.Combine(targetPath, name);
File.Copy(file, target, true);
}
Be sure to not confuse Date Modified with Date Created when looking for the file in a directory. It may look like it didn't get created if it has a Date Modified value.

Read file with partially unknown filename

I want to read in a text file but I only know a part of the filename. To be more specific, the format of the file is "FOO_yyyymmdd_hhmmss.txt" but when running my program, I will only know "FOO_yyyymmdd_" and ".txt". In other words, I want to read that file based on just the date, ignoring the "hhmmss" (time) part for I will not know the time of that file, only the date.
Here is part of what I have so far:
ArrayList al = new ArrayList();
string FileName = "FOO_" + DateTime.Now.ToString("yyyymmdd") + "_" ; //how do I correct this, keeping in mind that I need the time as well?
string InPath = #"\\myServer1\files\";
string OutPath = #"\\myServer2\files\";
string InFile = InPath + FileName;
string OutFile = OutPath + #"faceOut.txt";
using (StreamReader sr = new StreamReader(InFile))
{
string line;
while((line = sr.ReadLine()) != null)
{
al.Add(line);
}
sr.Close();
}
How can I read this file without knowing the whole string beforehand?
How about using a wildcard * available with DirectoryInfo.EnumerateFiles
string FileName = new DirectoryInfo(#"\\myServer1\files\")
.EnumerateFiles(String.Format("FOO_{0:yyyymmdd}_*.txt", DateTime.Now))
.FirstOrDefault()?.FullName;
FileName == null means that the file was not found
Note that the Null-Conditional Operator (?.) can only be used from C# 6.0 onwards
Well, search for the files, then check that theres's only one file to read:
var pathToSearch = #"\\myServer1\files\";
var knownPart = string.Format("FOO_{0:yyyymmdd}_", DateTime.Now);
var files = Directory
.EnumerateFiles(pathToSearch, knownPart + "??????.txt")
.Where(file => Regex.IsMatch(
Path.GetFileNameWithoutExtension(file).Substring(knownPart.Length),
"^(([0-1][0-9])|(2[0-3]))([0-5][0-9]){2}$"))
.ToArray();
if (files.Length <= 0) {
// No such files are found
// Probably, you want to throw an exception here
}
else if (files.Length > 1) {
// Too many such files are found
// Throw an exception or select the right file from "files"
}
else {
// There's one file only
var fileName = files[0];
...
}

Categories

Resources