I have a file hosted on the disk along with my website that I want to read .Not sure how do I access the file when I use System.Environment.CurrentDirectory it point to a D drive location .Can someone please tell me how can I get to my file stored at the root of where my site is hosted.
Thanks
There is an environment variable called HOME in your website's environment that will get you part way there.
You can access it using razor syntax or in code (C#). For example, suppose you have a file called data.txt that is at the root of your site with the default document and the rest of your files. You could get it's full path like this.
#{ var dataFileName = Environment.GetEnvironmentVariable("HOME").ToString() + "\\site\\wwwroot\\data.txt"; }
You can find this out on your own using the Site Control Management/"Kudu". For example, if your website is contoso.azurewebsites.net, then simply navigate to contoso.scm.azurewebsites.net. In here you can learn all about the file system and environment variables available to your website.
For testability, I use below code.
string path = "";
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HOME")))
path = Environment.GetEnvironmentVariable("HOME") + "\\site\\wwwroot\\bin";
else
path = ".";
path += "\\Resources\\myfile.json";
In above example, I added myfile.json file to Resources folder in a project with Content and Copy if newer property setting.
This works for me in both localhost and azure:
Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "file_at_root.txt");
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath is the full local path to your site's root.
I'm currently using AppDomain.CurrentDomain.BaseDirectory (.NET Core project). It returns "D:\home\site\wwwroot\" in Azure and the application root in local so the only difference is adding "bin\\" when it is Azure. I am searching the entire directory tree, just in case, but it can be trimmed.
It's something like:
private static string GetDriverPath(ILogger logger, string fileName)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
if (File.Exists(Path.Combine(path, fileName)))
{
return path;
}
string[] paths= Directory.GetFiles(path, fileName, SearchOption.AllDirectories);
if (paths.Any())
{
return Path.GetDirectoryName(paths.First());
}
throw new FileNotFoundException($"{fileName} was not found in {path}.", fileName);
}
I'm new answering questions and this is an old one but I hope it helps someone.
You can do it using the below code.
string fullFilePath = Environment.GetEnvironmentVariable("HOME") != null
? Environment.GetEnvironmentVariable("HOME") + #"\site\wwwroot\test.txt" //It will give the file directory path post azure deployment
: Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + #"\test.txt";//It will give the file directory path in dev environment.
Related
I am currently trying to build a electron app using Remix. Thanks to this great setup here https://github.com/itsMapleLeaf/remix-electron.
My requirements is as follows.
When the user uploads an asset, I store it inside a folder xyz in the app path. For mac is /Users/xyz/Application Support/app-folder/assets. I need to show these assets as image tags in electron view. But it fails to locate these files as the public folder is set to /build/. I tried using the file:/// protocol with absolute path but that didn't work as well.
The above repo has a config to set the public folder and that works, but then app stops working as it expects to find JS assets in /build/ folder. And I am not able to dynamically set the "publicPath" value in remix.config.js.
The solution I am looking for, is to have two public folders. 1. default /build/ folder and another one from app location. So remix can serve assets from both paths.
Any help is highly appreciated.
Thank you.
You'll need to update the remix-electron source.
In main.ts, you'll see where it gets all the asset files. You can include your other folders here. Note this is done at initialization, so any dynamically added files won't be included later. You'll need to export a function that lets you add to the asset files.
let [assetFiles] = await Promise.all([
collectAssetFiles(publicFolder),
collectAssetFiles(otherPublicFolder), // add additional folders
app.whenReady(),
])
https://github.com/itsMapleLeaf/remix-electron/blob/20352cc20f976bed03ffd20354c2d011e5ebed64/src/main.ts#L55-L58
Another option is to update the serveAsset function. This is called on every request with the path. You can then check your list of public folders for the asset. This will pickup any new files added.
export async function serveAsset(
request: Electron.ProtocolRequest,
files: AssetFile[],
): Promise<Electron.ProtocolResponse | undefined> {
const url = new URL(request.url)
// TODO: try different folders for list of files to check
const file = files.find((file) => file.path === url.pathname)
if (!file) return
return {
data: await file.content(),
mimeType: mime.getType(file.path) ?? undefined,
}
}
https://github.com/itsMapleLeaf/remix-electron/blob/20352cc20f976bed03ffd20354c2d011e5ebed64/src/asset-files.ts#L24-L37
I am using the accept property in the fileUpload control to only allow certain file Types and prevent uploading .exe or other potentially harmful files.
application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/pdf,text/plain,image/gif,image/jpeg,image/pjpeg,image/png"
This works, however I am using a Tool called Burp Suite that allows me to intercept an acceptable file eg .txt that could contain harmful code and change the filename extension to .exe which is then upload to the X-Page database.
When I goto save the document and after Interception and changing to a .exe, I have added the following code to identify an exe file:
Can we manipulate what has been uploaded and change the file extension to a harmless .txt ?
var fileData:com.ibm.xsp.http.UploadedFile =facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('fileUpload1'));
if (fileData != null) {
var tempFile:java.io.File = fileData.getServerFile();
// Get the path
var filePath:String = tempFile.getParentFile().getAbsolutePath();
// Get file Name
var fileName:String = tempFile.getParentFile().getName();
// Get the Name of the file as it appeared on the client machine - the name on the server will NOT be the same
var clientFileName:String = fileData.getClientFileName();
}
var fileRight = clientFileName.slice(-4);
if (fileRight == ".exe")
{
//facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('fileUpload1').replace(".exe",".txt"))
//facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('fileUpload1').remove(".exe",0))
}
Yes, you can. You have on the properties of control two options 'Use original file name of uploaded file' and 'Replace file name of uploaded file...' where you can put name with extension 'name.txt' . I didn't try to change only extension... That is probably better in code to replace.
I want to develop a windows phone based application in which I need to put the number of files in a folder (this folder is already a part of the project) to a list so that at run time I can access those files. If anybody can give me idea of how to do that then it will be great help.
In normal WPF applications we can write code like
DirectoryInfo di = new DirectoryInfo("D:\\Tempo");
FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories);
MessageBox.Show(fi.Length.ToString());
But Windows phone inside solution how do I do that?
I can get a single file access by this code
if (Application.GetResourceStream(new Uri("/WindowsPhone;component/Folder/file09.jpg", UriKind.Relative)) != null)
{
MessageBox.Show("Hi");
}
But inside that folder there are many files and I want to put them into list so at run time I can access those images. But the user won't be knowing about that so it should be a C# code, not a XAML code. Any help would be great.
It's pretty easy.
Make sure you add the specific folder to the Solution. Along with any files you want in that folder.
Make sure each file's Properties are set like so:
Build Action: Content
Copy to Output Directory: Do not copy
Make sure the application had loaded before calling
Lets say I had a folder called "Testfiles" and I want to read from it then:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
ReadAllFilesFromFolder("Testfiles");
}
// TODO: recursion to get subfolders and files (maybe?)
public async void ReadAllFilesFromFolder(string folder_name)
{
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assetsFolder = await package.GetFolderAsync(folder_name);
foreach (var file in await assetsFolder.GetFilesAsync())
{
// TODO: whatever you want to do with file
// string filename = file.Name;
}
}
In XPages, in the file upload control, after a user selects a file but before it's saved how can you get the filename? I'm not interested in the path as I believe that's not getable due to security issues but I would like to get the filename and extension if at all possible.
Thanks!
Actually you can get the file and fully manipulate it, read it, do whatever you want with it, its stored in the xsp folder on the server, to which you have read/write access... here is a code snippet that interacts with the file, I usually call from beforeRenderResponse...
var fileData:com.ibm.xsp.http.UploadedFile = facesContext.getExternalContext().getRequest().getParameterMap().get(getClientId('<INSERT ID OF UPLOAD CONTROL HERE (ie. fileUpload1)>'));
if (fileData != null) {
var tempFile:java.io.File = fileData.getServerFile();
// Get the path
var filePath:String = tempFile.getParentFile().getAbsolutePath();
// Get file Name
var fileName:String = tempFile.getParentFile().getName();
// Get the Name of the file as it appeared on the client machine - the name on the server will NOT be the same
var clientFileName:String = fileData.getClientFileName();
}
It sounds like you are referring to needing to get the data via CSJS, which you can do with the following code:
var filename = dojo.byId('#{id:fileUpload1}').value.split('\\').pop();
These links should be able to help you.
http://www.bleedyellow.com/blogs/andyc/entry/intercepting_a_file_upload4?lang=en
http://www.bleedyellow.com/blogs/m.leusink/entry/processing_files_uploaded_to_an_xpage?lang=en
I have written a controller action that checks for the existence of a PDF file and then returns the file (if found) to the browser as a download.
public ActionResult GetMyFile(string path)
{
if (String.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException("filename"); }
string downloadFileName = System.IO.Path.GetFileName(path);
// The worker process identity must have read access in both the file system and share
// otherwise this always returns false.
if (System.IO.File.Exists(path))
{
FilePathResult result =
File(path, System.Net.Mime.MediaTypeNames.Application.Pdf, downloadFileName);
return result;
}
return Content("no file", "text-plain");
}
Everything works fine, if the path parameter refers to a local path on disk (e.g. "D:\MyFolder\MyFile.pdf"), but when the path is a UNC path, the PDF is returned, but rendered as plain text in the browser.
Here's a snippet of what this looks like...
%PDF-1.3
1 0 obj
<<
/Length 1409
/Filter /FlateDecode
>
stream
X���I�%&/m�{J�J��t��$ؐ#�������iG#)�*��eVe]f#�흼��{����{����;�N'���?\fdl��J�ɞ!���?~|?"~Q�����"�Iw�Ow����:O��,��'?���dg|g/����P��t�Ӄ����:}��Ç������to���}�7��q��/�>O�>�_����9!�g������Y���|�{�p�?�������?����ܿO����s�>���'ڜH������;��D��>�� ���?��?J��t�m����t�C���O�(i�����H������~H��7JLǎ��K�%ͧ������T1�������S���=��.F.#�ww�����z�wǟҴ~���x�~���Px�������|3�j����c��)f1��O�1�4�����b�qN̔>������跟j�jB?��݃ ����c��.���ڀ�^ofq�,�Pp���g��=Oo�
��7�}��פ�> ��m)}�~�W!�w��Q�0SR�3���2-���&-��Fhy�S�]���HiyF_���
�4�;Q��l�f��|]>ۍ�hc��C��64���|L�4�9Pξ�{#-�?��|���=1Tl��O�����݂6�����a֡�.fe:�����/��1��#�{���������?��|v��}�4�}Cw��!����&z�v��4�����Uj0�&���-��������x�i�ģ����|=�9LnI7�&+�gʃ�;��U� m��
M��.�ޏ�D�QvT��ϯ���f���(��������0��������{_������ui�Rid�6���u��a��x"��m��{�o$����
����.���{#xu�8ӮR�����Ύ�r��{�m��$��O ��v����=�������X!~,E,�P����mf�2%9{��m����֍b���8���ñ��:
�PE��O<�e~jƄ�ߨ���?�Z�������"�Ǟ:����D��N�ߌ����PL��0��U����F4 g�oPW�Ml��#"�~ラ���_�����뾯���?���mGo�������=�bwGr/��b���?t3(�����t��=[\��O+���c������res����u��0�,G��f��̲qO��\�S��7��q̘�܀,.����Wn$��w�M%�����2ymd�I<͑U��eV�A-|�DڵDz�à�/]��J�|�ݾ'��$.\W��R�>���l|%�a�gj���0|{�R�c�������!�lwv?S��^S
E����z��3�����hr�{��R"C�݅o��Ac�*T��Q��IE�6XP5ˮ�j4k��v�
D��-��
endstream
Any thoughts as to why this might be happening?
My environment is an ASP.NET MVC 3 application running in IIS on Windows 7.
The client is Internet Explorer 9 RC running on the same machine.
The UNC path is a shared folder on the same machine as the web server, and is the same physical location used in the "local path test" (which succeeds).
For permissions I have ensured that the worker process identity for my application pool has Read permissions in both the file system and through the share.
I figured it out.
Changing the final return statement from:
return Content("no file", "text-plain");
to
return null;
Seems to have fixed the problem. Although I'm not sure as to why that is. I would think that if the first return (in the if block) was executed, then the final one would have never come into the picture.
I'm happy to accept someone else's answer if they can explain why that is.