Uploading Multiple Files to Azure Blob Storage - c#

Pretty new to Windows Azure. I've followed this tutorial: tutorial. It works perfectly however one limitation is that for the application I have in mind, it would need to be possible to upload multiple files relatively quickly.
Is it possible to modify the tutorial to support multi-file uploads, e.g. The user can use shift-click to select multiple files..
Or if anyone knows of any good tutorials detailing the above?
Any help is appreciated,
Thanks

I'd take a look at this tutorial from DotNetCurry which shows how to create a multiple file upload using jQuery to handle the multiple uploading of files to an ASP.NET page. It's built using ASP.NET 3.5, but it shouldn't matter if you're using .NET 4 - there's nothing too crazy going on.
But the key is that the jQuery plug-in will allow you to upload a collection of files to the server. The ASP.NET code behind will handle that by looping through the Request.Files collection:
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
System.IO.Path.GetFileName(hpf.FileName));
Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " +
hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
}
}
You would put this code in your tutorial in the insertButton_Click event handler - essentially putting the blob creation and uploading to blob storage inside the above code's if(hpf.ContentLength>0) block.
So pseudo-code may look like:
protected void insertButton_Click(object sender, EventArgs e)
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
// Make a unique blob name
string extension = System.IO.Path.GetExtension(hpf.FileName);
// Create the Blob and upload the file
var blob = _BlobContainer.GetBlobReference(Guid.NewGuid().ToString() + extension);
blob.UploadFromStream(hpf.InputStream);
// Set the metadata into the blob
blob.Metadata["FileName"] = fileNameBox.Text;
blob.Metadata["Submitter"] = submitterBox.Text;
blob.SetMetadata();
// Set the properties
blob.Properties.ContentType = hpf.ContentType;
blob.SetProperties();
}
}
Again, it's just pseudo-code, so I'm assuming that's how it would work. I didn't test the syntax, but I think it's close.
I hope this helps. Good luck!

Related

CreatDirectory or Delete directory is slower than code

Just a quick question if you can help me, please.
In C#, I am creating a directory, if it does not exist. In the next command, I am checking if the directory exists, I will copy some files.
The Problem is, to creating a new directory or Deleting it, takes time and slower than next code execution time.
The software gives an error of "The folder does not exist ".
I used Thread.Sleep(5000); to wait 5 seconds before copying the content to the directory.
It seems to be working but I feel like that this is not how it's supposed to be done. Does anyone know better coding?
string logDirectoryPath = Directory.GetCurrentDirectory() + "\\LogFiles";
if (!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
Thread.Sleep(5000);
}
if (Directory.Exists(Directory.GetCurrentDirectory() + "\\LogFiles"))
{
var s = logDirectoryPath + "\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(s))
{
w.WriteLine("--");
w.Write("\r\nLog Entry : ");
w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
}
}
//EDIT
JUST thought maybe I should use a loop?
While(!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
}
Use DirectoryInfo
DirectoryInfo di = new DirectoryInfo(#{PATHSTRING});
and use di.Exists to check it exists / di.Create() to create folder
and I'd like to recommend to use logDirectoryPath which you defined already.
like this
DirectoryInfo di = new DirectoryInfo(logDirectoryPath);
if ( !di.Exists ) {
di.Create();
}

Acces denied when FileUpload from temp folder to SPDocumentLibrary

As an unexperienced developer I have no idea whether this question is phrased properly (I did check the internet but I havent found a solution that worked for me that is why I signed up here). I am trying to make a form where users can upload files to attach to their form (in SharePoint 2013) and I used the following code as an example. The idea is to temporary accept the files and display them to the user and upload them to the document library when the form is submitted.
In my code however, this results in "acces denied" and when I debugged it, the following piece of my code seemed to be causing the problem:
public void BtnAttachmentUpload_Click(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
if (fileName != "")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (FileUpload.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + "\\" + _newfilePath;
FileUpload.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, DocNo, true);
DocNo = DocNo + 1;
Label.Text = "Successfully added in list";
}
}
The last line of the first section(FileUpload.PostedFile.SaveAs(_filepath);) is where it gives the following error:
"System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Spapps\AppData\Local\Temp\131613662837501509~testdoc2.pdf'
is denied.' "
Is this a known issue and is there a solution that can help me out?
Try with spsecurity.runwithelevatedprivileges
I've been looking to close this question but didnt find how to so Ill state it here as an answer. I havent found a solution, but I worked around this issue in my project by altering the approach; I do not temporarily upload and display the files anymore. They are deleted from the doclib if the procedure is cancelled.

open window explorer folder from my results c#

iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.

to create a gallery in asp.net by iterating through the folders

I want to create a gallery in asp.net the way it should work is as follows:
iterate through gallery folder
select all the folder and show them as albums with cover pic as thumbnail.jpg in that folder
when clicked on the album it should display the content of the folder (images).
My approach for creating this was to iterate through the folders and make views and link button based on that for albums and to display the content of album in that view as images using repeater control, but that didn't work out as it had many errors while implementing it. and I had to write the whole thing in on_init() function because of dynamic views.I can implement the html and js part (like for light box and other visual stuffs).
Please suggest some better approach maybe with some code example. Please use c# . Thanks
I can not just write you all the code... but ill give you a startup code:
int scanLVL = 4;//or however deep you need to go...
public void GetImageFromDir(string sourceDir, int startLVL)
{
if (startLVL <= scanLVL)
{
// Here you can process files found in the directory.
string[] fileEntries = Directory.GetFiles(sourceDir);
Label_showdata.Text +="<br />Dir:" + Path.GetFileName(sourceDir) ;
foreach (string fileName in fileEntries)
{
// do something with fileName
String tree = "";
for (int i = 0; i < startLVL; i++)
tree += " ";
Label_showdata.Text += "<br />" + tree + Path.GetFileName(fileName);
}
// Going in subdirectories of this directory.
string[] subdirEntries = Directory.GetDirectories(sourceDir);
foreach (string subdir in subdirEntries)
if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
GetImageFromDir(subdir, startLVL + 1);
}
}
This will print you on your web page(actualy in that Label_showdata) all the files and the directory where they are.
Basically from here you will need to wrap that data into a table and bind it in whatever control you feel comfortable with... Is not that hard actually... but it takes a bit more time to write exactly all the code (time that unfortunatlly i do not have at the moment...)

Process.Start is not working after hosting asp.net web application in IIS

I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.

Categories