Not able to creat folder and file via code in j2me - java-me

I am trying to create a folder and a image in j2me via code. I am able to creat a image file in Emulator, but when I tried to run that code in mobile(Nokia 2700)...it is giving exception. My code is as folloes.....
Enumeration e = FileSystemRegistry.listRoots();
String root = null;
while (e.hasMoreElements()) {
root = (String) e.nextElement();
break;
}
String newFilePath = "file:///"+root+fileName[i];
FileConnection fileConnection = (FileConnection) Connector.open(newFilePath,
Connector.READ_WRITE);
if(!fileConnection.exists())
fileConnection.create();
else if(fileConnection.fileSize() == mediaSize){
fileConnection.close();
continue;
}
What should I do for creat a image file in previously exist folder, or if possible, how could I creat a folder in j2me.

Some phones only allow creation of folders and files in certain subfolder(s) of root. You may not be allowed to create a folder or file in root on the Nokia 2700.
Typically, you have to go to the "Other" folder on these phones. So try one of these two for path and filename:
file:///c:/other/myfolder/myimage.jpg
file:///e:/other/myfolder/myimage.jpg
Depending on whether you want to save to the phone memory (drive c) or a memory card (drive e).

Related

FileSystemWatcher reports file available on network share but file cannot be found

BACKGROUND
I have a server that has a shared folder \\Server\Share with 4 subfolders:
OutboundFinal
OutboundStaging
InboundFinal
InboundStaging
All folders reside on the same physical disk and partition, no junction points used.
I also have several WinForms clients (up to 10) that write and read files to this share, each client is working on multiple threads (up to 5). Files are witten by clients (up to 50 threads altogether) into the \\Server\Share\OutboundStaging folder. Each file has the name of a GUID, so there's no overwriting. Once a file is completely written, it is moved by the client to the \\Server\Share\OutboundFinal folder. A Windows service running on the same server will pick it up, delete it, process it, then writes the file with the same name into the \\Server\Share\InboundStaging folder. Once the file is completely written, it is moved to the \\Server\Share\InboundFinal folder by the service.
This \\Server\Share\InboundFinal folder is monitored by each thread of each WinForms client using a FileSystemWatcher.WaitForChanged(WatcherChangeTypes.Changed | WatcherChangeTypes.Created, timeOut);
The FileSystemWatcher.Filter is set to the GUID filename of the file a certain thread expects to see in the \Server\Share\InboundFinal folder, so the FileSystemWatcher waits until a specific file is shown in the folder.
I have read several SO questions about FileSystemWatcher behaving erratically and not reporting changes on UNC shares. This is however not the case for me.
The code I use looks like this:
FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Path = InboundFinalFolder;
fileWatcher.Filter = GUIDFileName; // contains full UNC path AND the file name
fileWatcher.EnableRaisingEvents = true;
fileWatcher.IncludeSubdirectories = false;
var res = fileWatcher.WaitForChanged(WatcherChangeTypes.Changed | WatcherChangeTypes.Created, timeOut);
if (!fileWatcher.TimedOut)
{
using (FileStream stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) {
byte[] res = new byte[stream.Length];
stream.Read(res, 0, stream.Length);
return res;
}
It's the using line that throws the exception.
THE PROBLEM
I would assume that the fileWatcher.WaitForChanged would go on only if the file with the proper GUID name is in the \\Server\Share\InboundFinal folder. This is exactly how FileSystemWatcher works on local folders, but not with file shares accessed over the network (local files, even accessed via a share, also tend to work). FileSystemWatcher reports that the file the thread is waiting for is in the FileSystemWatcher \\Server\Share\InboundFinal folder. However, when I try to read the file, I get a FileNotFoundException. The reading thread has to wait 3-15 seconds before the file can be read. I try to open the file with a FileStream with Read sharing.
What could cause this behavior? How do I work around it? Ideally the FileSystemWatcher.WaitForChanged(WatcherChangeTypes.Changed | WatcherChangeTypes.Created, timeOut); should only continue execution if the file can be read or timeout happens.
The FileSystemWatcher has a bad reputation, but actually, it is not that bad...
1.)
Your code sample does not compile. I tried this:
FileSystemWatcher fileWatcher = new FileSystemWatcher();
fileWatcher.Path = "X:\\temp";
fileWatcher.Filter = "test.txt";
fileWatcher.EnableRaisingEvents = true;
fileWatcher.IncludeSubdirectories = false;
var res = fileWatcher.WaitForChanged(WatcherChangeTypes.Changed |
WatcherChangeTypes.Created, 20000);
if (!res.TimedOut)
{
FileInfo fi = new FileInfo(Path.Combine(fileWatcher.Path, res.Name));
using (FileStream stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
byte[] buf = new byte[stream.Length];
stream.Read(buf, 0, (int)stream.Length);
}
Console.WriteLine("read ok");
}
else
{
Console.WriteLine("time out");
}
I tested this where X: is a SMB share. It worked without problems (for me, see below).
But:
You should open / read the file with retries (sleeping for 100 ms after every unsuccessfully open). This is because you may run into a situation where the FileSystemWatcher detects a file, but the move (or another write operation) has not yet ended, so you have to wait until the file create / mover is really ready.
Or you do do not wait for the "real" file but for a flag file which the file move task creates after closing the "real" file.
2.)
Could it be that the move task did not close the file correctly?
3.)
Some years ago I had some tools (written in perl) where one script created a flag file and another script waited for it.
I had some nasty problems on a SMB 2 share. I found out that this was due to SMB caching.
See
https://bogner.sh/2014/10/how-to-disable-smb-client-side-caching/
File open fails initially when trying to open a file located on a win2k8 share but eventually can succeeed
https://technet.microsoft.com/en-us/library/ff686200.aspx
Try this (on the client):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanWorkstation\Parameters]
"DirectoryCacheLifetime"=dword:00000000
"FileNotFoundCacheLifetime"=dword:00000000
Save this as disablecache.reg and run regedit disablecache.reg
Then reboot.

play a downloaded mp3 in xamarin forms

I am able to play a file "test.mp3" added as a resource into the "Resources\Sounds\" folder of my pcl project by calling
AudioManager.Audio.Manager.PlaySound("test.mp3");
Now I am trying to play an audio file that I have downloaded from my webapi service. I am using the RestSharp library to download the file and the PCLStorage library to store the file:
try
{
var fileId = new Guid("test2");
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder resources = await rootFolder.CreateFolderAsync("Resources", CreationCollisionOption.OpenIfExists);
IFolder soundsFolder = await rootFolder.CreateFolderAsync("Sounds", CreationCollisionOption.OpenIfExists);
IFile myFile = await soundsFolder.CreateFileAsync($"{fileId}.mp3", CreationCollisionOption.ReplaceExisting);
using (var stream = await myFile.OpenAsync(fileAccess: FileAccess.ReadAndWrite))
{
var request = new RestRequest($"{fileId}");
var client = new RestClient();
client.BaseUrl = new System.Uri("http://10.0.2.2/MyApp.WebApi/api/");
var bytes = client.DownloadData(request);
foreach (var myByte in bytes)
{
stream.WriteByte(myByte);
}
}
}
catch (Exception e)
{
}
I also tried saving the file to the root dir but this also doesn't work.
The file seems to download just fine as far as I can tell (no errors). But I have yet to find a way to verify this by locating the file on the android emulator. I guess I first need to install the play store somehow and then download ES File explorer to see the file structure on the android emulator.
The problem is that when I try to play the soundfile in the same way I did with the embedded resource it won't work.
AudioManager.Audio.Manager.PlaySound("test2.mp3");
I guess this is because of the magic that happens during compile time to migrate the embedded resources to "somewhere" on the android emulator.
My main problem is that I do not understand what path to use to
write the file (tried resources/sounds and root)
read the file (tried
resources/sounds and root)
in order to be able to play the file
It turns out the AudioManager library assumes sounds are always Assets.
In it's NewSound method in the android code it tries to build an AssetFileDescriptor by using the following line:
Forms.Context.Assets.OpenFd(filePath);
I guess this method wants a filepath relative to the assets folder (for compiled resources) and throws a FileNotFoundException otherwise. This exception, however thrown, did not reach my catch statement in my pcl code. (it looks like it get's swallowed somewhere in the android -> pcl layer??)
Now I am using the SoundPool.LoadAsync with a filepath rather than a AssetFileDescriptor and this fixes my problem.
Yay!

How to get local file system path in azure websites

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.

How can I count the files inside a folder of project solution?

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;
}
}

PDF is plain-text/encoded mess when downloaded from UNC share (using ASP.NET MVC 3 / IE 9)

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.

Resources