Windows 8 StorageFile.GetFileFromPathAsync Using UNC Path - file

Has anyone EVER managed to use a windows 8 app to copy files from a unc dir to a local dir ?
According to the official documentation here
It is possible to connect to a UNC path
I am using the std FILE ACCESS sample and have changed one line of code to read as below
I have added all the capabilities
Added .txt as a file type
The UNC path is read write to everyone and is located on the same machine..
But I keep getting Access Denied Errors.
Can anyone possibly provide me with a working example
This is driving me mad and really questioning the whole point of win 8 dev for LOB apps.
TIA
private async void Initialize()
{
try
{
//sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
string myfile = #"\\ALL387\Temp\testfile.txt";
sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(myfile);
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}

I have sorted this out and the way I found best to do it was to create a folder object
enumnerate over the files in the folder object
copy the files one at a time to the local folder then access them
It seems that you can't open the files, but you can copy them. ( which was what I was trying to achieve in the first place )
Hope this helps
private async void Initialize()
{
try
{
var myfldr = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(#"\\ALL387\Temp");
var myfiles = await myfldr.GetFilesAsync();
foreach (StorageFile myfile in myfiles)
{
StorageFile fileCopy = await myfile.CopyAsync(KnownFolders.DocumentsLibrary, myfile.Name, NameCollisionOption.ReplaceExisting);
}
var dsd = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in dsd)
{
StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path);
}
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}

Related

How to fix "FileSystemException: Cannot open file" in flutter when reading and writing files?

I'm pretty new to dart/flutter, so let me know if there is anything I can clarify. I'm trying to download a file, but when I try to access it, I get the error
FileSystemException: Cannot open file, path = './data.csv' (OS Error: Read-only file system, errno = 30)
What am I doing wrong, and how can I fix this?
downloadTextFile() {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse('I put the link I used here, but it is sort of long'))
.then((HttpClientRequest request) {
return request.close();
})
.then((HttpClientResponse response) {
response.pipe(new File('./data.csv').openWrite());
});
readFileByLines();
}
void readFileByLines() {
File file = new File('./data.csv');
List<String> lines = file.readAsLinesSync();
lines.forEach((l) => print(l));
}
You can use package https://pub.dev/packages/path_provider
And write your file to tempPath or appDocPath
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
For Android , In AndroidManifest.xml , you can add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Check if file exists on Android device with Kotlin

I'm newbie in Android development and doing on my first Android project and faced with .txt file handling.
I succesfully created a txt file on Android Emulator, which is stored in: /storage/emulated/0/Android/data/com.example.test/files/test.txt
My problem is, I don't know how to test with code if this file exists. I write next few lines, which I found on the Internet:
fun checkIfFileExists() {
val fileName2 = "test.txt"
var file = File(filesDir, fileName2)
var fileExists = file.exists()
if(fileExists) {
println("File exists")
}
else {
println("File doesn't exists")
}
}
Function for file saving:
btnSave.setOnClickListener(View.OnClickListener {
val file:String = fileName.text.toString()
val data:String = fileData.text.toString()
val fileOutputStream:FileOutputStream
try {
fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE)
fileOutputStream.write(data.toByteArray())
}catch (e: FileNotFoundException){
e.printStackTrace()
}catch (e: NumberFormatException){
e.printStackTrace()
}catch (e: IOException){
e.printStackTrace()
}catch (e: Exception){
e.printStackTrace()
}
Toast.makeText(applicationContext,"data save",Toast.LENGTH_LONG).show()
fileName.text.clear()
fileData.text.clear()
})
But it always prints "File doesn't exists", although I checked myself and file exists.
Hope someone knows what I did wrong.
You instantiated the file with only the file name and no path, so how can it know where to look? On Android you don't want to be working with the absolute paths but with what the Context gives you.
Not sure how you created your original file, but assuming it was saved to internal storage, you would do this (getFilesDir() is a Context method, so will be available if calling from an Activity):
var file = File(getFilesDir().getAbsolutePath(), fileName2)

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

File exists but program throws a FileNotFoundException

/*
*This program checks type casting from String to int/double from a file
*/
import java.io.*;
import java.lang.String;
public class ConvertingStringsToNums {
public static void main (String[] args){
File dataFile = new File("/files/scores.dat");
FileReader in;
BufferedReader readFile;
String score;
double avgScore, totalScores = 0;
int numScores = 0;
//------------------------------------------------------------
try {
in = new FileReader(dataFile);
readFile = new BufferedReader(in);
while((score = readFile.readLine()) != null) {
numScores += 1;
System.out.println(score);
totalScores += Double.parseDouble(score);
}
avgScore = totalScores / numScores;
readFile.close();
in.close();
} catch(FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
} //end try/catch
}
}
1) If you wish to open a file at an absolute file path on your hard drive:
br = new BufferedReader (
new FileReader(
new File ("/files/scores.dat")));
2) If you wish to open a file at an relative path relative to where you started your app:
br = new BufferedReader (
new FileReader(
new File ("files/scores.dat")));
3) If you wish to open a file at an relative path relative to your class files (particularly relevant for packages and/or for executing from a .jar or a .war):
this.getClass().getResourceAsStream ("files/scores.dat");
'Hope that helps
The reason is can be that you wont be having permission to open the file.
try chmod 755 scores.dat from terminal in order to change the permissions and see if the error still exist.
The answer to this problem exists in the javadocs for the File class:
For UNIX platforms, the prefix of an absolute pathname is always "/". Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix "/" and an empty name sequence.
In your code, you have the following:
File dataFile = new File("/files/scores.dat");
According to the documentation, this is an absolute path, which means Java is looking for a folder at the root of the filesystem called "files" and then looking for scores.dat in that folder.
If you instead expect to search for a files directory that is relative to the current directory, you'd need to omit the first /:
File dataFile = new File("files/scores.dat");
The other option is to use an absolute path to your data file, but you may run into problems if you change the location of your project or put the class files in a JAR file.
Try turning up your logging level to DEBUG or ALL so that you can see exactly where the program is trying to look. This will help you adjust your code to target the right folder.

FileStream seems to find an unexisting file

I have this code:
public static string GetUserEmail()
{
string path = Application.StartupPath + "\\mail.txt";
MessageBox.Show(path);
string adres = String.Empty;
if (File.Exists(path))
{
using (StreamReader sr = new StreamReader(path))
{
adres = sr.ReadLine();
}
}
else
{
using (FileStream fs = File.Create(path))
{
using (StreamReader sr = new StreamReader(path))
{
adres = sr.ReadLine();
}
}
}
MessageBox.Show(adres);
return adres;
}
I checked the ApplicationPath with the MessageBox.Show(); as you can see, go there and delete the file, re-launch the app, and it still reads the previous line . I uninstall the app re-install and still seems to find the file and read the same line I have entered in the very first installation. I searched windows, the whole C drive, there is no mail.txt and it still finds the mail.txt and reads the line (a email address, used to identify the user)
What can it be? aliens?
Firstly, which code route does the program take? The one where the file is created, or the one where the existing file is read?
Try placing a breakpoint just before the existance of the file is checked and then go and check at that point if the file exists or not.
Do you have any code elsewhere that creates and writes the file, as part of the application startup?
Otherwise, its definitely aliens.

Resources