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!
}
}
Related
I want fill form which have upload profile image and other controls like Name,address
I am using angular 8 for client side and asp.net core for backend..
I want viewmodel which contains all properties.
I have used angular8 for uploading image in formdata.I have gone through https://www.techiediaries.com/angular-formdata/.My main question is how to receive uploaded file in ViewModel not in httpRequest.Form.Files["ImageFile"]
[HttpPost("Create")]
public IActionResult CreateApplication(ApplicationModel model)
{
//want to capture uploaded image
return Ok();
}
See this tutorial, can be very helpful: Click
Here is way how i`d do it:
[HttpPost]
public async Task<IActionResult> AddBodyType([FromForm]ApplicationModel model)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest();
}
else
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
await stream.FlushAsync();
}
model.ImagePath = dbPath;
await _context.Add(model);
return Ok();
}
else
{
return BadRequest();
}
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
Ok got it, the problem was that the directory names were not fixed, they were created by the newly created Id of the product, so the solution was to carry out a check for the directory and if it's not there, create it.
For example
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
Once it's created with the new Id it can be used/found.
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
we have string example :
www.example.com/default.aspx?code-1/price-2/code-4/
i want to get integers from code and price and save to list of integers.
for example , 1 and 4 are codes , 2 is price for filter in site.
InBetween = GetStringInBetween("Brand-", "/", Example, false, false);
please help me.
Below is a simple program that completes your requirement.
class Program
{
public void GetCodesAndPrice(string url,out List<int> listOfCodes, out List<int> listOfPrice )
{
listOfCodes=new List<int>();
listOfPrice = new List<int>();
url = url.Substring(url.IndexOf('?')+1);
var strArray = url.Split('/');
foreach (string s in strArray)
{
if(s.ToLower().Contains("code"))
listOfCodes.Add(GetIntValue(s));
else if(s.ToLower().Contains("price"))
listOfPrice.Add(GetIntValue(s));
}
// Now you have list of price in "listOfPrice" and codes in "listOfCodes",
// If you want to return these two list then declare as out
}
public int GetIntValue(string str)
{
try
{
return Convert.ToInt32(str.Substring(str.IndexOf('-') + 1));
}
catch (Exception ex)
{
// Handle your exception over here
}
return 0; // It depends on you what do you want to return if exception occurs in this function
}
public static void Main()
{
var prog = new Program();
List<int> listOfCodes;
List<int> listOfPrice;
prog.GetCodesAndPrice("www.example.com/default.aspx?code-1/price-2/code-4/", out listOfCodes,out listOfPrice);
Console.ReadKey();
}
}
It is complete console program. Test it and Embed in your program. Hope this will help you
I have a Upload component in which I´m supposed to import a xml file in order to parse it.
I´m trying to use the File.createTempFile method to create the file phisically,but something weird is going on.
For example,if I take the file named "test.xml" and use the createTempFile method to create it on the disk,the name of the generate file becomes something like 'test.xml13234xml'.How can I create the file the correct way?
This is expected when using i.e. createTempFile method as it implicitly creates a file with random prefix:
// a part of createTempFile method
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir) {
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
return new File(dir, prefix + Long.toString(n) + suffix);
}
which should give something like 'test.xml13234xml'.
If you want to create a file with the correct name and keep it for later use you can rename/move it within uploadSucceeded method.
public class ExampleUpload implements Upload.Receiver, Upload.SucceededListener {
private Upload xmlUpload;
private File tempFile;
public ExampleUpload() {
this.xmlUpload = new Upload("Upload:", this);
this.xmlUpload.addSucceededListener(this);
}
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
try {
tempFile = File.createTempFile(filename, "xml");
tempFile.deleteOnExit();
return new FileOutputStream(tempFile);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void uploadSucceeded(SucceededEvent event) {
try {
File destinationFile = new File("c:\\" + event.getFilename());
FileUtils.moveFile(tempFile, destinationFile));
// TODO read and parse destinationFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
I don't have any knowledge on working with Sqlite database on Blackberry. Recently i delved into database with Blackberry. When i tried to create the database, the database gets successfully created on Simulator(Simulate-->ChangeSDCard-->MountDirectory) on Some particular folder.
Next when i try to Open the database for creating tables & inserting data--
String db_url ="file:///SDCard/Databases/"+"sampleTest.db";
db = DatabaseFactory.open(db_url);
It through the DatabaseException error with message :"Invalid path name. Path does not contains a proper root list. See FileSystemRegistry class for details."
Please help me !! What is going Wrong here.
First set Sdcard in Simulator:
Go Simulate-->change sdcard-->Add directories(sdcard folder path)
Write Query like this:
public Vector GetData()
{
Cursor c = null;
Statement st = null;
Vector tableVector=new Vector();
try
{
URI myURI = URI.create("/SDCard/" + "abc.db");
d = DatabaseFactory.open(myURI);
st= d.createStatement("Query"););
st.prepare();
c = st.getCursor();
Row r;
while(c.next())
{
r = c.getRow();
tableVector.addElement(r.getString(0));
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
}
finally
{
try {
c.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
try {
st.close();
} catch (DatabaseException e) {
e.printStackTrace();
}
try {
d.close();
} catch (DatabaseIOException e) {
e.printStackTrace();
}
}
return tableVector;
}