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.
Related
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());
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];
...
}
The process cannot access the file because it is being used by another process
private void DeleteReport()
{
int invid = Convert.ToInt32(Session["InvId"]);
string FileName = invid + "_Report" + ".pdf";
string path1 = Server.MapPath("~/Report/" + FileName);
if (File.Exists(path1))
{
File.Delete(path1);
}
}
The error tells you, that the file is used and can't be deleted. So nothing wrong. As you did not formulate a
real question, lets try to help you in following way.
I guess that only your program is using the report, so good possible, you block the report
somewhere else.
E.g., the following code
string path = "C:\\Temp\\test.txt";
FileStream file = File.Open(path, FileMode.OpenOrCreate);
if (File.Exists(path))
File.Delete(path);
raises the same error. It does not necessarily mean that the process is another process.
What you can do is for example, for testing purpose, install SysInternal
http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx and add following code around your
File.Delete statement. Then you will see, what process uses the file:
try
{
File.Delete(path);
}
catch (Exception)
{
using (Process tool = new Process())
{
tool.StartInfo.FileName = #"C:\Program Files (x86)\SysinternalsSuite\handle.exe"; //Your path
tool.StartInfo.Arguments = path + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process p = Process.GetProcessById(int.Parse(match.Value));
MessageBox.Show(p.ProcessName); // OR LOG IT
}
}
throw;
}
Credit for handle.exe call to https://stackoverflow.com/a/1263609/2707156
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.
Can someone tell me what is going to happen in this code when an error is encountered? Ideally it should continue the foreach statement until it gets to the last record, but I suspect it's stopping in the middle of the operation because when I check the number of files moved it's off by 225. If it is in fact stopping because of an error, what can I do to make it continue the loop?
I'm creating a new upload manager for our software and need to clean the old files up. There are about 715 orphaned files equaling around 750 MB after a year and a half of use because the original developers didn't write the code to correctly overwrite old files when a new one was uploaded. They also saved the files in a single directory. I can't stand that so I'm moving all of the files into a structure - Vessel Name - ServiceRequesetID - files uploaded for that service. I'm also giving the users a gridview to view and delete files they no longer need as they work the service.
protected void Button1_Click(object sender, EventArgs e)
{
GridViewRow[] rowArray = new GridViewRow[gv_Files.Rows.Count];
gv_Files.Rows.CopyTo(rowArray, 0);
int i = -1;
foreach(GridViewRow row in rowArray)
{
i++;
string _serviceRequestID = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_SRID")).Text;
string _vesselName = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_VesselID")).Text;
string _uploadDIR = Server.MapPath("uploadedFiles");
string _vesselDIR = Server.MapPath("uploadedFiles" + "\\" + _vesselName);
string _fileName = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_FileName")).Text;
DirectoryInfo dInfo = new DirectoryInfo(_uploadDIR);
DirectoryInfo dVessel = new DirectoryInfo(_vesselDIR);
DirectoryInfo dSRID = new DirectoryInfo(_serviceRequestID);
dInfo.CreateSubdirectory(_vesselName);
dVessel.CreateSubdirectory(_serviceRequestID);
string _originalFile = _uploadDIR + "\\" + _fileName;
string _fileFullPath = Path.Combine(Server.MapPath("uploadedFiles/" + _vesselName + "/" + _serviceRequestID + "/"), _fileName);
FileInfo NewFile = new FileInfo(_fileFullPath);
string _fileUploadPath = _vesselName + "/" + _serviceRequestID + "/" + _fileName;
string sourceFile = _originalFile;
FileInfo _source = new FileInfo(sourceFile);
string destinationFile = _fileFullPath;
try
{
{
File.Move(sourceFile, destinationFile);
movefiles.InsertNewUploadPath(Convert.ToDecimal(_serviceRequestID), 1, _fileUploadPath);
}
}
catch (Exception ex)
{
CreateLogFiles Err = new CreateLogFiles();
Err.ErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message);
}
}
_utility.MessageBox("Completed processing files.");
}
As long as the error encountered occurs within the try catch clause, the code will continue executing within the foreach loop. However, if the error occurs outside of the try catch, the function will exit and throw an error. How many files does your error log report??