0

I'm suffered from making text files with UWP. I've experienced how to make a text file in UWP.

but when I tried to make own my program, I got some problems with Creating File. I don't know where is the reason from. the lack of my knowledge about C# class p? or misuse of builtin Class(like storageFile etc...) function?

I made my application to read files from device and save as a another file.

but It doesn't work at all.

when I use break point to figure out what is problem.

Picture1. outputFile is setted as a null

you can see i.outputFile(type StorageFile) is setted as a null. but with my intent, it shouldn't be remained as a null. because I set its(i's) outputFile with member function called "setOutFile(StorageFolder)". you can see in the picture above.

below is my source code which handle my ClassType. it stops when meet FileIO.WriteTextAsync ... because i.outPutFile is null.

public async Task<List<string>> DoRandom(FileLists fl, StorageFolder folder)
    {
        FileLists retLists = new FileLists();
        List<string> encodingList = new List<string>();

        foreach (UploadedFile i in fl)
        {
            // read stream from storagefile
            Stream s = await i.originFile.OpenStreamForReadAsync(); 

            // streamreader from stream
            StreamReader sr = new StreamReader(s, Encoding.ASCII);

            i.setOutFile(folder);
            if (sr.CurrentEncoding == Encoding.ASCII)
            {
                encodingList.Add("ASCII   " + i.outputName);
            }
            string str = await sr.ReadToEndAsync();
            StringBuilder stringBuilder = new StringBuilder(str);

            if (Option1)
            {
                doOption1(stringBuilder);
            }
            await FileIO.WriteTextAsync(i.outputFile, stringBuilder.ToString());
            if (Option1);
        };
        return encodingList;
    }

in Uploaded Class (you can just see setOutFile function).

 class UploadedFile
{
    public StorageFile originFile;
    public StorageFile outputFile { get; set; }

    public string inputName {get; private set; }
    public string outputName {get; private set; }
    public string fileSz{get; private set;}

    public UploadedFile(StorageFile storageFile)
    {
        originFile = storageFile;
        inputName = storageFile.Name;
    }

    public async Task GetFileSz()
    {
        var bp = await originFile.GetBasicPropertiesAsync();
        this.fileSz = string.Format("{0:n0} Byte", bp.Size);
    }

    public async void setOutFile(StorageFolder folder)
    {
        var rand = new Random();
        string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder result = new StringBuilder(13);

        for (int i=0; i<13; i++)
        {
            result.Append(charset[rand.Next(charset.Length)]);
        }
        StringBuilder outputName = new StringBuilder();

        outputName.Append(inputName.Substring(0, inputName.Length - 4));
        outputName.Append("_");
        outputName.Append(result);
        outputName.Append(".txt");
        this.outputName = outputName.ToString();

        outputFile = await folder.CreateFileAsync(outputName.ToString(), CreationCollisionOption.ReplaceExisting);

        for (int i = 0; i <= 10000; i++) // break point
            i++;
    }

when I insert a assignment(below) in constructor.

outputFile = storageFile;

it barely make a file in target directory with purposed fileName. but it has no data in it!!!..... I tried with below source Code but it has no data in it, either.

await FileIO.WriteTextAsync(i.outputFile, "constant String");

my app makes file with edited constructor, but it has no data in it.

I don't know what is my problem, C# Class syntax or ...what?

Jeong Yo Han
  • 551
  • 4
  • 16
  • uwp has limited number of locations on users device where u can write files, make your the location u r trying to write is accesible to ur app, if u try to write outside of allowed folders ur app will get an "access is denied" exception – Muhammad Touseef Aug 21 '18 at 15:53
  • @touseefbsb but, the directory is just a folder in Desktop(I get it with FolderPicker). isn't Desktop folder allowed to UWP App? – Jeong Yo Han Aug 21 '18 at 16:04
  • https://stackoverflow.com/questions/33082835/windows-10-universal-app-file-directory-access says i can have permission for folder which is selected by FolderPicker – Jeong Yo Han Aug 21 '18 at 16:10
  • 1
    even when i set folder with " StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; " It doesn't work – Jeong Yo Han Aug 21 '18 at 16:14
  • 1
    ahan then it seems problem is not the permission, something else is causing the problem and yes when u get something with folderpicker it is allowed for that run of the app, but in general Desktop folder is not allowed to write for uwp. – Muhammad Touseef Aug 21 '18 at 18:58
  • 1
    There's a lot of auxiliary code you've provided here. It may be helpful to test out just the file writing part in a different test project. You might also want to pull down and test out the Samples on FileAccess from the official platform samples which show how to write data out to files. See the [ApplicationData](https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/ApplicationData) and [FileAccess](https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/FileAccess) ones in particular. – Michael Hawker - MSFT Aug 21 '18 at 21:06

1 Answers1

1

Thanks all of you, guys who commented on my posts. I desperately tried to figure out what is problem, I met. I carefully read your comments and I think your advice is definitely good.

but the problem that I met was, Straightforwardly, sync,async- matter thing. I struggled with this problem with more than 5 hours, and I found the class's member function setOutfile has async function "StorageFoder.CreateFileAsync" and when the machine read that statement, It create asynchronously and begin to write some text(implemented in handler class) on It even It's not created.

...In myType Class, I changed my member function's type from async void to async Task.

 public async Task setOutFile(StorageFolder folder)
    {
        var rand = new Random();
        string charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        StringBuilder result = new StringBuilder(13);

        for (int i=0; i<13; i++)
        {
            result.Append(charset[rand.Next(charset.Length)]);
        }
        StringBuilder outputName = new StringBuilder();

        outputName.Append(inputName.Substring(0, inputName.Length - 4));
        outputName.Append("_");
        outputName.Append(result);
        outputName.Append(".txt");
        this.outputName = outputName.ToString();

        if (folder != null)
        {
            outputFile = await folder.CreateFileAsync(outputName.ToString(), CreationCollisionOption.ReplaceExisting);
        }

    }

and then in handler class member function, i just added await keyword before i.setOutFile(StorageFolder ..)

       public async Task<List<string>> DoRandom(FileLists fl, StorageFolder folder)
    {
        FileLists retLists = new FileLists();
        List<string> encodingList = new List<string>();

        foreach (UploadedFile i in fl)
        {
            // read stream from storagefile
            Stream s = await i.originFile.OpenStreamForReadAsync(); 

            // streamreader from stream
            StreamReader sr = new StreamReader(s, Encoding.ASCII);

            await i.setOutFile(folder) ; // wait until setOutFile ends
            if (sr.CurrentEncoding == Encoding.ASCII)
            {
                encodingList.Add("ASCII   " + i.outputName);
            }
            string str = await sr.ReadToEndAsync();
            StringBuilder stringBuilder = new StringBuilder(str);

            if (Option1)
            {
                doOption1(stringBuilder);
            }
            await FileIO.WriteTextAsync(i.outputFile, stringBuilder.ToString());
            if (Option1);
        };
        return encodingList;
    }

and It works, thanks all you guys.

Jeong Yo Han
  • 551
  • 4
  • 16
  • My issue was different from yours. I was downloading a file and saving it in the application's local folder. But it was not working properly, the application was getting stuck while creating the file. My return type was Task which I changed to Task then it started working. Thanks – Shrikant Dandile Jun 03 '20 at 05:46