How to Delete from from folder in wcf - c#

i have a web app to upload files to one folder. Now I want to delete the file from that folder using a WCF service. In asp.net we use string filePath = Server.MapPath(FPath); but this is not working in WCF.
Any help?

I'm guessing you just need to change it to:
string filePath = HttpContext.Current.Server.MapPath(FPath)

Related

C# File Upload works locally; not on Azure

I have a C# web application which uploads an image file to Azure Blob Storage. I am passing the local path of image file from a textbox (no File Upload Controller). This application works locally as expected. But when I publish it on Azure, it throws exception.
Could not find file (filename)
What changes should be made to run it on Azure?
Code :
CloudBlobContainer container = Program.BlobUtilities.GetBlobClient.GetContainerReference(Container);// container
container.CreateIfNotExists();
container.SetPermissions(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
CloudBlobDirectory directory = container.GetDirectoryReference(foldername);
// Get reference to blob (binary content)
CloudBlockBlob blockBlob_image = directory.GetBlockBlobReference(imageid);
using (var filestream = System.IO.File.OpenRead(image_path))
{
blockBlob_image.UploadFromStream(filestream);
}
Could not find file (filename)
The exception is caused by System.IO.File.OpenRead(filePath), as you Web Application is published to Azure. If you want use System.IO.File.OpenRead(filePath), you need to make sure that the filepath could be found in the WebApp.
What changes should be made to run it on Azure?
If you want to use the code on the Azure, you need to make sure that the file could be found in the Azue Website. You need to copy the file to Azure. If you want to upload file to the Azure blob, it is not recommanded. Since that you need to copy the file to Azure WebApp first.
Also As you mentioned that you could use FileUpload Controller to do that.
You're probably using the path to your computer which will be different on azure. You can try change the path to something like this:
string path = HostingEnvironment.ApplicationPhysicalPath + #"\YourProjectName\PathToFile"
Ok, Found the solution. Instead of passing file path to a textbox, I used FileUpload Controller. In the code-behind,
Stream image_path = FileUpload1.FileContent;
Actually, earlier too I had tried using FileUpload controller, but Server.MapPath(FileUpload1.Filename) and Path.GetFullPath(FileUpload1.FileName) were not giving the correct path.
Also,
using (var filestream = image_path)
{
blockBlob_image.UploadFromStream(image_path);
}
is replaced by
blockBlob_image.UploadFromStream(image_path);

Save files to external(other domain server) server in asp.net

Is it possible to save file to other domain path from file control. I have 2 website www.domain1.com & www.domain2.com. Now I have file control in www.domain1.com & here I want to upload a file which will be store in some directory of www.domain2.com. I don't know is it possible or not. I am trying below basic code but it's not working
if (mainImageUploader.FileName != "")
{
System.IO.FileInfo file = new System.IO.FileInfo(mainImageUploader.PostedFile.FileName);
string newname = file.Name.Remove((file.Name.Length - file.Extension.Length));
newname = (newname + System.DateTime.Now.ToString("_ddMMyyhhmmss")) + file.Extension;
mainImageUploader.SaveAs(Server.MapPath("http://www.domain2.com/images/client-store/" + path + newname));
}
No, not possible if your other server is configured anywhere near correctly.
You need to enable endpoint on your other server to provide file upload. And probably need to secure it somehow - i.e. with username/password.
It's not possible. The better way is creating a WebApi to save file on its server on your second website and save file via calling it from your first website.
Each web server only let to each website to access to its root and subfolders or files.

Share File To Dropbox from Application (MVC C#)

Is there any way I can share file to user's dropbox folder ?
What I exactly want to implement is as below:
User Click on Dropbox icon.
Then Dropbox Asks for His/Her Dropbox account details.
File from Application Saved to his/her dropbox account.
I did search dropbox API's But did not get anything which helps me to save to user's Dropbox account.
I read API Documentation ,
https://www.dropbox.com/developers-v1/core/docs#files_put
, Here i can save files to my dropbox but not to other.
please guide me on the same. thanks in advance.
I don't know if version 2 is any better for your purposes, but version 1 of the API is deprecated
If the user has their Dropbox integrated with Explorer, then I would think you can just write to the local folder and it will sync up to Dropbox as usual.
You can use the Dropbox API to have a user authorize your app to access their Dropbox account and then programmatically save files to the account. (This works even if the user doesn't have the official Dropbox app installed.)
For .NET, we recommend using the official Dropbox API v2 .NET SDK:
https://www.dropbox.com/developers/documentation/dotnet
The tutorial shows how to upload a file:
https://www.dropbox.com/developers/documentation/dotnet#tutorial
Here is the Code snippet I Used to save Dropbox. I hope this will help mates.
// Code to retrieve Dropbox Local Folder
var infoPath = #"Dropbox\info.json";
var jsonPath = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), infoPath);
if (!System.IO.File.Exists(jsonPath)) jsonPath = Path.Combine(Environment.GetEnvironmentVariable("AppData"), infoPath);
if (!System.IO.File.Exists(jsonPath)) {
return "-2";
}
var dropboxPath = System.IO.File.ReadAllText(jsonPath).Split('\"')[5].Replace(#"\\", #"\");
string fileName = "Your FileName";
string sourcePath = Server.MapPath("Source Path Here");
string targetPath = dropboxPath;
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, "filename.extention");
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.File.Exists(destFile))
{
System.IO.File.SetLastWriteTime(destFile, DateTime.Now);
}

asp.net MVC3 create folder where application can write in

I need to create a folder to use for storing files within it, in a .Net MVC3 application, but I think the problem is common to all ASP.Net platform.
Problem is I can create the folder, but cannot write the files, because System.UnauthorizedAccessException occurred.
I also tryed givin extra permission to the user currently running the web app, but nothing changes.
This is my code so far:
if (!System.IO.Directory.Exists(fullPath))
{
System.IO.Directory.CreateDirectory(fullPath);
var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
var userName = user.Translate(typeof(System.Security.Principal.NTAccount));
var dirInfo = new System.IO.DirectoryInfo(fullPath);
var sec = dirInfo.GetAccessControl();
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(userName,
System.Security.AccessControl.FileSystemRights.Modify,
System.Security.AccessControl.AccessControlType.Allow)
);
dirInfo.SetAccessControl(sec);
System.IO.Directory.CreateDirectory(fullPath);
}
string fullPathFileName = System.IO.Path.Combine(fullPath, fileName);
System.IO.File.WriteAllBytes(fullPath, viaggio.Depliant.RawFile);
Too bad, last line of code always throw System.UnauthorizedAccessException.
I'm not impersonating user in my app, everything run under a predefined user.
What should I do to create a folder and assure that the application can also create files within it?
Edited:
I also tryed to save the files in the App_Data special folder, but I still got the System.UnauthorizedAccessException error. Somebody can tell me why is that happening?
I hate to answer my own question when the problem is that stupid...
I'm just trying to save a file without a proper filename: you can see I'm using the fullPath variable both for creating the folder and for saving the file, instead of using the correctly created fullPathFileName.
Blame on me!
Use App_Data folder, quote from http://msdn.microsoft.com/en-us/library/06t2w7da%28v=vs.80%29.aspx :
To improve the security of the data used by your ASP.NET application, a new subfolder named App_Data has been added for ASP.NET applications. Files stored in the App_Data folder are not returned in response to direct HTTP requests, which makes the App_Data folder the recommended location for data stored with your application, including .mdf (SQL Server Express Edition), .mdb (Microsoft Access), or XML files. Note that when using the App_Data folder to store your application data, the identity of your application has read and write permissions to the App_Data folder.

How to map a windows service program's file

I am working on a windows service c# program.
I need to use a file. Here is my code
const string mail_file_path = #"template\mailbody.html";
But according to my log, there is an error like this:
Error: Could not find a part of the path 'C:\Windows\system32\template\mailbody.html'.
I use the app.configuration to use another file
<add key="TimeStampFilePath" value="timestamp.ini" />
StreamReader sr = new StreamReader(ConfigurationManager.AppSettings["TimeStampFilePath"]);
But I can't read the file.
When I run this project as a simple windows console project, it works. But after I run it using windows service mode, the two problems appear.
You could try:
// dir is path where your service EXE is running
string dir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
// mail_file_path is where you need to search
string mail_file_path = Path.Combine(dir , #"\template\mailbody.html");
Take my answer as an integration to #CharithJ's post, which is definitely correct!!
If you have got template\mailbody.html in the same directory where the service exe resides. Try something like below and see. You could find the folder where the windows service .exe resides.
string mail_file_path = System.Reflection.Assembly.GetEntryAssembly().Location +
"\template\mailbody.html";
Or this also can help AppDomain.CurrentDomain.BaseDirectory
I found a way to solve the problem, thanks to the suggestion from #Macro. I get the windows service mapping directory using REGISTER API, then setting the working directory the same with it. Then I can use the relative path to get the file I need.

Categories