Here is my code
[HttpPost]
public ActionResult Result(FormCollection form)
{
String Date = form["date"].ToString();
String Directory = Date.Replace("-", "");
//Featch file path
String RootPath = Properties.Settings.Default.FilePath.ToString();
String FilePath = System.IO.Path.Combine(RootPath, Directory, "Call.Log.txt");
FilePath = #System.IO.Path.GetFullPath(FilePath).ToString();
if (System.IO.File.Exists(FilePath))
{
string[] lines = System.IO.File.ReadAllLines(FilePath);
foreach(string line in lines)
{
System.Diagnostics.Debug.WriteLine(line);
}
return null;
} else
{
return View("DirNotFound");
}
//return null;
}
I'm receiving date as 2015-07-27 from form. And D:\ from RootPath. As FilePath output I'm getting D:\\20150727\\Call.Log.txt. The file is really exists in the directory but I'm getting false as System.IO.File.Exists(FilePath). I need your suggestion to fix the issue.
Related
I am working with files on C# and I got to a point where I don't know how to continue anymore.
The scenario is this: If I upload 3 or more files with the same name at the same time, I want to handle them and change their name to from "myfile.pdf" to "myfile.pdf(1)/(2)/(3)..." depending on how much files I upload.
This is what I have tried so far and in this case, this only works for only the second file because when the third one comes, it will check there is any file with the same - yes, okay name it "myfile.pdf(2) - but this exists too so it will go to another place.
How can I achieve having the same three files in the same folder with this naming convention?
Here's what I have tried so far:
string FileName = "MyFile.pdf";
string path = #"C:\Project\MyPdfFiles\"
if (File.Exists(path))
{
int i = 1;
var FileExists = false;
while (FileExists==false)
{
if (FileExists == false)
{
FileName = FileName + "(" + i + ")";
}
else
return;
i++;
}
}
And the result of this code is: "MyFile.pdf", "MyFile.pdf(1)" And the third one doesn't load here.
I think I'm missing something in the loop or idk :(.
Can someone help me?
I have tried also this:
if(File.Exists(path) || File.Exists(path+"(")
//because when the second file its uploaded, its name will be SecondFile.pdf(1), so this will return true and will proceed running, but still the iteration will "always" start from 0 since everytime I upload a file, I have to refresh the process.
Don't use return inside your while loop, better set 'FileExists = true' whenever you want you loop to stop. A return statement will exit your current method.
I think your problem can be easily solved using recursion, something like this (untested):
public class Program
{
public string FileName { get; set; }
public Program() {
string fileName = "MyFile.pdf";
string path = #"C:\Project\MyPdfFiles\";
FileName = CheckFileName(path, fileName);
}
public string CheckFileName(string path, string fileName, int iteration = 0) {
if (File.Exists($"{path}{fileName}")) {
iteration++;
CheckFileName(path, $"{fileName}({iteration})", iteration);
}
return fileName;
}
}
What this does is: it CheckFileName method will keep calling itself until it finds a name that doesn't exist yet.
This should do the job.
public class Program
{
public static string GetUnusedFilePath(string directorypath, string filename, string ext)
{
string fullPath = $"{directorypath}{filename}{ext}";
int inc = 0;
// check until you have a filepath that doesn't exist
while (File.Exists(fullPath))
{
fullPath = $"{directorypath}{filename}{inc}{ext}";
inc++;
}
return fullPath;
}
public static void UploadFile(string filepath)
{
using (FileStream fs = File.Create(filepath))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
fs.Write(title, 0, title.Length);
}
}
public static void Main()
{
string[] filestoUpload = { "file", "file", "file", "anotherfile", "anotherfile", "anotherfile" };
string directorypath = #"D:\temp\";
string ext = ".txt";
foreach(var file in filestoUpload)
{
var filePath = GetUnusedFilePath(directorypath, file, ext);
UploadFile(filePath);
}
}
}
I solved this by creating new folders with special names using the code below:
DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(FileDirectory);
FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + FullFileName + "*");
int i = filesAndDirs.Length;
if (i>1)
{
FileName = Filename + "(" + i ")";
}
So what this does is that it will count how many files we have in that folder with the same name, so I have to check if we have more than 1 file, then change it's name to file(1).
Thank you to everyone that tried to help me, much appreciated.
I have a .csv file as the attached image which has a list of folders and files . I would like to read the .csv file and recreate the same folder structure under different folder.
Say for example I have C:\Data\SourceFolder\Folder2\Folder4\File1.txt , I would like the file to be moved to C:\Data\FilesCopiedfromC\SourceFolder\Folder2\Folder4\File1.txt . In the above destinaton path , the C:\Data\FilesCopiedfromC is going to be the same always . I am able to create the folder structure in the destination but when I do the file.move from source to destination I get a "File cannot be created when it already exists error".
try
{
string inputfile = textBox1.Text.ToString();
using(StreamReader reader = new StreamReader(inputfile))
{
string headerline = reader.ReadLine();
Boolean firstline = true;
string line = string.Empty;
string SourceFileNameCSV;
string SourceFilePathCSV,totalSourceFilePath, strConstructedDestinationfullpath;
string[] parts;
while ((line = reader.ReadLine()) != null)
{
char[] delimiters = new char[] { ',' };
parts= line.Split(delimiters);
if (parts.Length > 0)
{
SourceFilePathCSV = parts[0];
SourceFileNameCSV = parts[1];
totalSourceFilePath = SourceFilePathCSV + "\\" + SourceFileNameCSV;
strDestinationDynamicPath = SourceFilePathCSV.Replace("C:\\Data\\", " ").TrimEnd();
strConstructedDestinationfullpath = Path.Combine(strDestinationStaticPath, strDestinationDynamicPath);
if (!string.IsNullOrEmpty(strConstructedDestinationfullpath))
{
if (!Directory.Exists(strDestinationDynamicPath))
{
Directory.CreateDirectory(strConstructedDestinationfullpath);
}
// File.Move(totalSourceFilePath, strConstructedDestinationfullpath);
}
}
}
}
}//try
Any help is appreciated.
You need to specify a file name for the destination, currently you are just providing a path:
File.Move(
totalSourceFilePath,
Path.Combine(strConstructedDestinationfullpath, Path.GetFileName(totalSourceFilePath));
It's because, apparently, the file already exists in the destination. What you can do is check if the file exists an delete if so:
if (System.IO.File.Exists("filename"))
{
//delete
System.IO.File.Delete("filename"); //try/catch exception handling
needs to be implemented
}
I am trying to upload an image file on an online link of a domain i have bought. Link is live. I can upload it in a local directory. but not working for online link. I cant find the correct way to give online path of my online directory to command
string filePath = HttpContext.Server.MapPath("???");
here is the code.
[HttpPost]
public ActionResult UpdateBanners(UpdateBanners banner)
{
zasa_company_slider sliderData = new zasa_company_slider();
if (banner != null && banner.file.ContentLength > 0)
{
string filePath = HttpContext.Server.MapPath("http://ak.eat-ax.com/akpanel/images/" + Path.GetFileName(banner.file.FileName));
banner.file.SaveAs(filePath);
}
return RedirectToAction("Index");
}
Retrieve your images like this
string filePath = Server.MapPath("~/Images/" + Path.GetFileName(index.FileName));
index.SaveAs(filePath);
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
foreach (string var in filePaths)
{
if (Path.GetFileName(var) == index.FileName)
{
sliderData.SLIDER_IMAGE = ("liveServerURL/" + Path.GetFileName(var));
}
}
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);
}
We have a process from third-party vendor to drop sales and invetory data everyday and could have any of the following scenarios
Drop the right file. (Naming standard: test.xls)
Drop the right file but not follow the right naming standard. (Other
names could be test_mmddyyyy or testmmddyyyy)
No file dropped.
I am trying to build my logic around these scenarios and stuck at how to build my logic when the file exists but does not have the right naming standard and check for this condition and change the name of the file to the appropriate naming standard.
public void Main()
{
try
{
string filefullpathname = #"C:\Temp\test.xls";
if (File.Exists(filefullpathname) == false)
{
Console.WriteLine("File does not exist in the path");
}
// file exists but right naming standard not followed (Other names could be test_mmddyyyy or testmmddyyyy)
// how to check for this condition and change the name of the file to the naming standard
else
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
string fullname = filename.FullName;
bool ind = Path.HasExtension(fullname);
if (ind == false)
{
File.Move(fullname, directory + filepartialname + ".xls");
}
else
{
File.Move(fullname, directory + filepartialname + ".xls");
}
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
It is not really clear as to if it is only the file name or a missing extension. So I put in both.
public void Main()
{
try
{
string dirname = #"C:\Temp\";
DirectoryInfo directory = new DirectoryInfo(dirname);
string filepartialname = "test";
FileInfo[] fileindirectory = directory.GetFiles(filepartialname + "*");
foreach (FileInfo filename in fileindirectory)
{
if (filename.Extension == "")
{
//doesn't have an extension
}
else if (!Regex.IsMatch(filename.Name.Replace(filename.Extension, ""), #"^[A-Z|a-z]$"))
{
//contains more then just test
}
else
{
//file is good
}
}
}
catch (Exception error)
{
Console.WriteLine(error);
}
}
Your explanation of what your inputs could be, and how you want to move those inputs isn't super clear, but this should get you started:
var expectedFilename = Path.Combine(someOtherDirectory, "test.xls");
// Matches test* and *.xls
var relevantFiles = Directory
.EnumerateFiles(searchDirectory, "*", SearchOption.TopDirectoryOnly)
.Where(f => Path.GetFileName(f).StartsWith("test") || Path.GetExtension(f).Equals(".xls"))
foreach (var file in relevantFiles)
{
// If there's more than one file matching the pattern, last one in wins
File.Move(file, expectedFilename);
}