Count Total Folder in asp.net - asp.net

I need to read a folder that contains multiple inner folders, which have more than 100 xml files. I need to read all these xml files one by one. I am using asp.net c# . How can I achieve this.
For Example: A is my folder, containing 1,2,3,4,5,6...200 as sub-folders.
Now the folder 1 contains a.xml, b.xml, c.xml ... Similarly folder 2 contains 1.xml, 2.xml, 3.xml ...
Now I need to read all these xml files one by one from each folder.

you can make use of parallel linq and do as below
int count = 0;
string[] files = null;
try
{
files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("You do not have permission to access one or more folders in this directory tree.");
return;
}
catch (FileNotFoundException)
{
Console.WriteLine("The specified directory {0} was not found.", path);
}
var fileContents = from file in files.AsParallel()
let extension = Path.GetExtension(file)
where extension == ".xml"
let text = File.ReadAllText(file)
select new FileResult { Text = text , FileName = file }; //Or ReadAllBytes, ReadAllLines, etc.
try
{
foreach (var item in fileContents)
{
Console.WriteLine(Path.GetFileName(item.FileName) + ":" + item.Text.Length);
count++;
}
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException)
{
Console.WriteLine(ex.Message);
return true;
}
return false;
});
}
Example takem from : https://msdn.microsoft.com/en-us/library/ff462679%28v=vs.110%29.aspx

Related

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

List folderName and file contents in listview

Is there a way to list the subfolders and its files in a asp.net listview without using a Sql table?
Thanks
Assume that you have a listview named ListView1
You can do it with something like the following to list filenames.:
static void ListFiles(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
{
string fileName = Path.GetFileNameWithoutExtension(f);
ListViewItem item = new ListViewItem(fileName);
item.Tag = f; //could get folder name: DirectoryInfo(d).Name
ListView1.Items.Add(item);
}
ListFiles(d);
}
}
catch (System.Exception ex)
{
// handle exceptions here!
}
}

Downloading Multiple files from FTP Server using JSCH

I want to download all the files from FTP server using JSCH.
Below is the code snippet,
List<File> fileList = null;
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remoteFolder);
for (ChannelSftp.LsEntry file : list) {
if( getLog().isDebugEnabled() ){
getLog().debug("Retrieved Files from the folder is"+file);
}
if (!(new File(file.getFilename())).isFile()) {
continue;
}
fileList.add(new File(remoteFolder,file.getFilename())) ;
return fileList;
The method will return List, for another method to download the files from the remote server using sftpChannel.get(src,dest) ;
Please let me know if the code is ok.
I don't have an environment to test, so can't confirm it.
But somewhat similar code i wrote for FTPClient and it works.
Appreciate your help.
You can use SftpATTRS to get the file information. You can declare a wrapper class to store file information. An example shown below.
private class SFTPFile
{
private SftpATTRS sftpAttributes;
public SFTPFile(LsEntry lsEntry)
{
this.sftpAttributes = lsEntry.getAttrs();
}
public boolean isFile()
{
return (!sftpAttributes.isDir() && !sftpAttributes.isLink());
}
}
Now you can use this class to test if the LsEntry is a file
private List<SFTPFile> getFiles(String path)
{
List<SFTPFile> files = null;
try
{
List<?> lsEntries = sftpChannel.ls(path);
if (lsEntries != null)
{
files = new ArrayList<SFTPFile>();
for (int i = 0; i < lsEntries.size(); i++)
{
Object next = lsEntries.get(i);
if (!(next instanceof LsEntry))
{
// throw exception
}
SFTPFile sftpFile = new SFTPFile((LsEntry) next);
if (sftpFile.isFile())
{
files.add(sftpFile);
}
}
}
}
catch (SftpException sftpException)
{
//
}
return files;
}
Now you can use sftpChannel.get(src,dest) ; to download files.

List all files, dirs and subdirs with tomahawk tree

I've been using tomahawk (1.1.11) for a project. I want to display a tree with all the files and subdirs (and files in those subdirs). I have a code, but it's not listing all of the files and dirs, and don't know where's the mistake.
public TreeNode getTreeData() {
path = loadConfiguredPath();
String dependencia = userVerifier.getDependencia();
if (dependencia.equals("TEST")) {
path = path + "dataFiles";
} else {
path = path + "dataFiles\\" + dependencia;
}
dirRoot = new File(path);
treeRoot = new TreeNodeBase("folder", "BASEDIR", false);
createTree(dirRoot, treeRoot);
return treeRoot;
}
private void createTree(File fileRoot, TreeNode treeRoot) {
File[] files = fileRoot.listFiles();
TreeNodeBase tnb;
for (File f : files) {
if (f.isDirectory()) {
tnb = new TreeNodeBase("folder", f.getName(), false);
treeRoot.getChildren().add(tnb);
createTree(f, tnb);
}
if (f.isFile()) {
tnb = new TreeNodeBase("file", f.getName(), false);
treeRoot.getChildren().add(tnb);
//return;
}
}
return;
}
UPDATE: code corrected as mention in comment.
Sorry, finally found my error !
I was returning when just one file was found. and I just change that return at the end of the for loop.
Thanks anyway

"File not found exception" trying to extract zip archive with DotNetZip

public void ZipExtract(string zipfilename, string outputDirectory)
{
using (ZipFile zip = ZipFile.Read(zipfilename))//file not found exception
{
Directory.CreateDirectory(outputDirectory);
zip.ExtractSelectedEntries("name=*.jpg,*.jpeg,*.png,*.gif,*.bmp", " ",
outputDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
[HttpPost]
public ContentResult Uploadify(HttpPostedFileBase filedata)
{
var path = Server.MapPath(#"~/Files");
var filePath = Path.Combine(path, filedata.FileName);
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}
filedata.SaveAs(filePath);
// CreateThumbnail(filePath);
_db.Photos.Add(new Photo
{
Filename = filedata.FileName
});
_db.SaveChanges();
return new ContentResult{Content = "1"};
}
I try to extract the uploaded zip archive and save extracted files in a folder but "file not found" exception happens all the time. What's the mistake?
Have you tried setting a break point here, and see what value filedata.FileName has? (And see if it actually exists on the server.)
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}

Resources