Count images in Folder using ASP.net - asp.net-mvc

I want to count the number of images a folder folder, but it produces this error :
Could not find a part of the path 'c:\Content\slideshow\images\image\'.
All of the images are in a folder in the project. Located a Content/slideshow/images/image
This is my code:
<%
string dir = #"/Content/slideshow/images/image";
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dir);
numFiles = files.Length;
Response.Write("num ber of images :" + numFiles);
%>

"Could not find a part of the path
'c:\Content\slideshow\images\image\'"
Means very simply that the folder does not exist. If you want to user a relative path you can do the following.
Server.MapPath("~/{RelativePathHere})
Edit : In response to your comment. You will need to loop through the file and check for file extension of each (Keeping your own count)

Use HttpContext.Current.Server.MapPath to map the virtual path to physical path and then pass it to Directory.GetFiles method

To call Directory.GetFiles() you need to pass the full path to the images directory.
string dirPath = #"~/Content/slideshow/images/image";
string dirFullPath = Server.MapPath(dirPath);
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
Response.Write("number of images: " + numFiles);
Server.MapPath returns the entire physical file path associated to the dirPath virtual path.

You need to pass this as a relative path using Server.MapPath
Then I would suggest using DirectoryInfo.GetFiles instead of Directory.GetFiles and filter on the image types that you want, so you don't count non-image files. This will yield a FileInfo[].
<%
string dir = Server.MapPath(#"/Content/slideshow/images/image");
FileInfo[] files;
int numFiles;
files = (new System.IO.DirectoryInfo(dir)).GetFiles("filePattern");
numFiles = files.Length;
Response.Write("num ber of images :" + numFiles);
%>
If you have multiple file types that you want to count the best way to do this is just to remove the pattern then filter the results.
var extensions = new String[] {"jpg", "png", "gif"};
files = (new System.IO.DirectInfo(dir)).GetFiles();
foreach(var extension in extensions)
{
numFiles += files.AsEnumerable.Where(f => f.Extension.Equals(extension));
}

int numberOfFiles ;
string path = "C:/PIC";
numberOfFiles = System.IO.Directory.GetFiles(path).Length;
Check Now

Related

Lua ranme files before extension

Im having issues on renaming a file with a tag before the extension
here is the filename sample i want to rename:
AudiA6.bin
My current code name tag is "---Tuned"
And returning it like this:
AudiA6.bin---Tuned
I want it to handle the file like this:
AudiA6---Tuned.bin
here is my smaple:
if (OpenProjectVersion (olsnaam, 1versienummer)) then -- "1" => cast to integer
if (projectExport (output_path..inputfile.."---Tuned", eFiletypeBinary)) then
OUTPUT:write ("done"); --File exported successfully
projectClose();
gevonden = "1";
if (OpenProjectVersion (olsnaam, 1versienummer)) then -- "1" => cast to integer
if (projectExport (output_path..inputfile.."---Tuned", eFiletypeBinary)) then
OUTPUT:write ("done"); --File exported successfully
projectClose();
gevonden = "1";
local fileName = "AudiA6.bin"
local tag = "---Test"
local newFileName = fileName:gsub("(.*)(%.%w+)", "%1".. tag .. "%2")
print(newFileName)
Please read the Lua manual

Naming convention for variables containing file path or its parts

What are standard or most self-descripting variable names for variables with following values? (Consider them from perspective of File.Ext)
// Windows environment
var0 = "C:\Folder_A\Folder_B\Folder_C\File.Ext"
var1 = "C:\"
var2 = "C:\Folder_A\"
var3 = "C:\Folder_A\Folder_B\"
var4 = "C:\Folder_A\Folder_B\Folder_C\"
var5 = "File"
var6 = "Ext"
var7 = ".Ext"
This is what comes to my unexperienced mind:
FullPath
Drive
???
???
ParentFolderPath
Filename
Extension
FullExtension
Also what is Windows standard or best practice for storing folder paths - with or without the last \?
Same for extension - with or without .?
filePath = "C:\Folder_A\Folder_B\Folder_C\File.Ext"
rootDirectory = "C:\"
directoryPath = "C:\Folder_A\"
anotherDirectoryPath = "C:\Folder_A\Folder_B\"
aThirdDirectoryPath = "C:\Folder_A\Folder_B\Folder_C\"
filenameSansSuffix = "File"
fileSuffix = "Ext"
anotherDefinitionOfFileSuffix = ".Ext"
It is more natural to define directory paths without a trailing backslash.
When it comes to file extensions I usually include the dot. Also, in Windows Batch scripting, for instance, the modifier ~x results in the file extension including the dot (when i tried it).
%~xI Expands %I to a file name extension only.
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/for

How can one to dynamically parse a CSV file using C# and the Smart Format Detector in FileHelpers 3.1?

As per in this FileHelpers 3.1 example, you can automatically detect a CSV file format using the FileHelpers.Detection.SmartFormatDetector class.
But the example goes no further. How do you use this information to dynamically parse a CSV file? It must have something to do with the DelimitedFileEngine but I cannot see how.
Update:
I figured out a possible way but had to resort to using reflection (which does not feel right). Is there another/better way? Maybe using System.Dynamic? Anyway, here is the code I have so far, it ain't pretty but it works:
// follows on from smart detector example
FileHelpers.Detection.RecordFormatInfo lDetectedFormat = formats[0];
Type lDetectedClass = lDetectedFormat.ClassBuilderAsDelimited.CreateRecordClass();
List<FieldInfo> lFieldInfoList = new List<FieldInfo>(lDetectedFormat.ClassBuilderAsDelimited.FieldCount);
foreach (FileHelpers.Dynamic.DelimitedFieldBuilder lField in lDetectedFormat.ClassBuilderAsDelimited.Fields)
lFieldInfoList.Add(lDetectedClass.GetField(lField.FieldName));
FileHelperAsyncEngine lFileEngine = new FileHelperAsyncEngine(lDetectedClass);
int lRecNo = 0;
lFileEngine.BeginReadFile(cReadingsFile);
try
{
while (true)
{
object lRec = lFileEngine.ReadNext();
if (lRec == null)
break;
Trace.WriteLine("Record " + lRecNo);
lFieldInfoList.ForEach(f => Trace.WriteLine(" " + f.Name + " = " + f.GetValue(lRec)));
lRecNo++;
}
}
finally
{
lFileEngine.Close();
}
As I use the SmartFormatDetector to determine the exact format of the incoming Delimited files you can use following appoach:
private DelimitedClassBuilder GetFormat(string file)
{
var detector = new FileHelpers.Detection.SmartFormatDetector();
var format = detector.DetectFileFormat(file);
return format.First().ClassBuilderAsDelimited;
}
private List<T> ConvertFile2Objects<T>(string file, out DelimitedFileEngine engine)
{
var format = GetSeperator(file); // Get Here your FormatInfo
engine = new DelimitedFileEngine(typeof(T)); //define your DelimitdFileEngine
//set some Properties of the engine with what you need
engine.ErrorMode = ErrorMode.SaveAndContinue; //optional
engine.Options.Delimiter = format.Delimiter;
engine.Options.IgnoreFirstLines = format.IgnoreFirstLines;
engine.Options.IgnoreLastLines = format.IgnoreLastLines;
//process
var ret = engine.ReadFileAsList(file);
this.errorCount = engine.ErrorManager.ErrorCount;
var err = engine.ErrorManager.Errors;
engine.ErrorManager.SaveErrors("errors.out");
//return records do here what you need
return ret.Cast<T>().ToList();
}
This is an approach I use in a project, where I only know that I have to process Delimited files of multiple types.
Attention:
I noticed that with the files I recieved the SmartFormatDetector has a problem with tab delimiter. Maybe this should be considered.
Disclaimer: This code is not perfected but in a usable state. Modification and/or refactoring is adviced.

Wildcard file search in WScript

I need to get all the files in a folder that match a certain wildcard pattern, using JScript. For example:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var folderName = "C:\\TRScanFolder\\";
var folder = fso.GetFolder(folderName);
var searchPattern = "1001-*POD*.*"
// Now I need a list of all files matching the search pattern
I know I could iterate through the folder.Files collection and test the names against a regex, but I would prefer to just get Windows to do a search and get only the ones matching. This is mostly for performance, since there could be several hundred files in the folder, but only a few will be the ones I want.
Is there a function or something that I can use to do a search? Or should I stick with a loop and regex?
Edit: Here I what I got to work with a regex. Is there a way to do it without?
var regex = /^1001-.*POD.*\..*$/i;
var files = new Enumerator(folder.Files);
for (files.moveFirst(); !files.atEnd(); files.moveNext())
{
var fileAttachment = files.item();
if (regex.test(fileAttachment.Name))
{
// Do stuff
}
}
One alternative is to shell out to the command line and use the dir command.
var wsh = new ActiveXObject("WScript.Shell");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var dirName = "C:\\someFolder";
var pattern = "s*";
var fileName;
var oExec = wsh.Exec('%comspec% /c dir /on /b "' + dirName + '\\' + pattern + '"');
// wait for dir command to finish
while (oExec.Status === 0) {
WScript.Sleep(100);
}
// process output
while (!oExec.StdOut.AtEndOfStream) {
fileName = oExec.StdOut.ReadLine();
if ( fso.FileExists(fso.BuildPath(dirName, fileName)) ) {
//do stuff
WScript.Echo(fileName);
}
}

Get path and filename of all files in a given dir and its subdirs

I was given this code a while back. I finally got around to testing it (with some changes to put the files in a different place)...
void AddFiles(AnsiString path/*, TDataSet *DataSet*/)
{
TSearchRec sr;
int f;
f = FindFirst(path+"\\*.*", faAnyFile, sr);
while( !f )
{
if(sr.Attr & faDirectory)
{
if(sr.Name != "." && sr.Name != "..")
{
path.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(path/*, DataSet*/);
}
}
else
{
Form1->ListBox1->Items->Add(path+ "\\"+ sr.Name);
//DataSet->Append();
//DataSet->FieldByName("Name")->Value = sr.Name;
/* other fields ... */
//DataSet->Post();
}
f = FindNext(sr);
}
FindClose(sr);
}
It doesn't work properly. In the beginning it gets mixed up..
a real structure of...
root
root\subdir1
root\subdir2
root\subdir3
gets messed up like this...
root
root\subdir1
root\subdir1\subdir2
root\subdir1\subdir2\subdir3
and eventually it stops including the root or sub\sub folders and 'path' just contains a subfolder (without its root folders)
this is completely useless for aquring useable full-path filenames.
so either can you tell me where the code is going wrong... or give me some advice on how to get the full path filenames in a dir and all its subdirs.
I want it to be as basic as possible. i.e. no uncommon advanced c++ features. stuff that a builder noob is likely to be able to debug.
Here you append each subpath to the current path:
path.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(path/*, DataSet*/);
Use a new variable for the combined path, so you don't mess up the path variable you still need for the rest of the files/dirs in the directory:
AnsiString subpath;
subpath.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(subpath/*, DataSet*/);

Resources