I am writing code to copy an mp3 file into the local folder of an application. I am trying to use the CopyAsync method to do this, but a red squiggly line appears underneath this method and I'm unsure of how to fix it. The error specifies that there is no accessible extension method. It then advises if I'm missing an assembly reference or a user directive.
I've found extensive information on this method through Microsoft, so I know it's possible. I'm brand new to building apps in C#, so I am not quite sure how to fix it.
My code is included below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
namespace MusicLibraryTest
{
public static class LibraryHelper
{
public static async void ChooseMusic()
{
//Music Library is opened on user's computer and displays all available mp3 files
var picker = new Windows.Storage.Pickers.FileOpenPicker
{
ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail,
SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.MusicLibrary
};
picker.FileTypeFilter.Add(".mp3");
//File is copied to local folder for use in music library
var file = picker.PickSingleFileAsync();
if (file != null)
{
await file.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
Change this line:
var file = picker.PickSingleFileAsync();
To
var file = await picker.PickSingleFileAsync();
You're calling an async method that should be awaited.
Related
Im having an issue with using DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open is not opening a spreadsheet, it returns a file not found exception. The class i'm using has worked many times before, but i've never used it in a UWP project.
I've created a simple example and found that I get the same issue when using File.Exists i've include all the using statements i use if that helps.
Does anyone know why the File.Exists cannot detect the file?
and yes i've triple checked the file does exist on D:!
C# UWP Project created using UWP Template Studio [MainPage.xaml.cs]
using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using UWP_APP.ViewModels;
using Windows.UI.Xaml.Controls;
namespace UWP_APP.Views
{
public sealed partial class MainPage : Page
{
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainPage()
{
InitializeComponent();
string filePath = #"D:\example.xlsm";
if (File.Exists(filePath))
{
int a = 1;
}
else
{
int a = 0;
}
}
Does anyone know why the File.Exists cannot detect the file?
UWP app is running in sandbox, because File.Exists is System.IO api. So it could not work for accessing file except ApplicationData.Current.LocalFolder. If you do want to check if the file exist in the specific path, we suggest you add broadFileSystemAccess capability and enable in the system file access setting. This capability works for APIs in the Windows.Storage namespace.
And using the flolowing method to check if the file exist.
try
{
var file = StorageFile.GetFileFromPathAsync(#"C:\Users\Karan\OneDrive\Desktop\2010.pdf");
if (file != null)
{
isExist = true;
}
}
catch (Exception)
{
isExist = false;
}
I'm trying to use SharpCompress to read .rar files from my UWP application. It works fine on network shares from which I can read the archive no problem, but I get System.UnauthorizedAccessException on files anywhere on the local system including for instance USB drives. I have access to the files by other methods e.g. StorageFile. It makes no difference whether BroadFileSystemAccess is on or off. I've tried in both C# and Vb.net Here's the code of my test app in C#. The exception occurs at ArchiveFactory.Open.
I can also read Zip files no problem using the .net Compression methods but they can't do rar files, hence needing SharpCompress.
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using SharpCompress;
using Windows.Storage.Pickers;
using Windows.Storage;
using SharpCompress.Archives;
namespace TestRAR
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
OpenRAR.Click += OpenRAR_Clicked;
}
public async void OpenRAR_Clicked(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".rar");
picker.FileTypeFilter.Add(".cbr");
picker.FileTypeFilter.Add(".cbz");
picker.FileTypeFilter.Add(".zip");
StorageFile pickfile = await picker.PickSingleFileAsync();
if (pickfile == null) { return; }
string pth = pickfile.Path;
FileInfo pickInfo = new FileInfo(pth);
try
{
ListRARs.Items.Clear();
using (var Arch = ArchiveFactory.Open(pickInfo))
{
foreach (IArchiveEntry a in Arch.Entries)
{
string thisKey = a.Key;
ListRARs.Items.Add(thisKey);
}
}
}
catch{ }
}
}
}
This is the first time I've used SharpCompress and I'm completely stumped. Any ideas anyone?
I have a simple UWP app that I want to open a folder to access all the files in with. I'm using the stock example code from Microsoft for how to make a folder picker in UWP. However, after picking the folder (any folder) and trying to access it I always get this exception:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'T:\temp' is denied.
Source=System.IO.FileSystem
StackTrace:
at System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String path, Boolean ignoreNotFound)
at System.IO.Enumeration.FileSystemEnumerator`1..ctor(String directory, EnumerationOptions options)
at System.IO.Enumeration.FileSystemEnumerable`1..ctor(String directory, FindTransform transform, EnumerationOptions options)
at System.IO.Enumeration.FileSystemEnumerableFactory.FileInfos(String directory, String expression, EnumerationOptions options)
at System.IO.DirectoryInfo.InternalEnumerateInfos(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions options)
at System.IO.DirectoryInfo.EnumerateFiles()
at ShutterShock.MainPage.<Button_Click>d__1.MoveNext() in C:\Users\nixca\source\repos\ShutterShock\ShutterShock\MainPage.xaml.cs:line 37
Mainpage.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace ShutterShock
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string path = await GetOpenLocation();
var boop = new DirectoryInfo(path);
boop.EnumerateFiles();
}
async Task<string> GetOpenLocation()
{
string returnText;
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
// Application now has read/write access to all contents in the picked folder
// (including other sub-folder contents)
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder);
returnText = folder.Path;
}
else
{
returnText = "Operation cancelled."; //todo make this an exception, catch that exception
}
return returnText;
}
}
}
I get the exception on the "boop.EnumerateFiles();" line.
So of course right after posting this it came to me, but I'll leave this up because I didn't actually find an answer anywhere before asking. The Microsoft example is dumb, and unless all you want is the path of the folder, returning the path is useless. The UWP filepicker doesn't actually grant you System.IO level access to the folder, all it gives you is a StorageFolder you can work on. If you want to do anything useful, you need to return the StorageFolder object, you can use that to actually work on files. This is probably obvious to people who actually know what they're doing.
If you wan to get all files in a selected folder, then you can use folder.GetFilesAsync().
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
var files = await folder.GetFilesAsync();
foreach(var file in files)
{
Debug.WriteLine(file.Path);
}
}
Here is the my result.
I am trying to develop C# Google Vision API function.
the code is supposed to compile into dll and it should run to do the following steps.
get the image from the image Path.
send the image to Google vision api
Call the document text detection function
get the return value (text string values)
Done
When I run the dll, However, it keeps giving me an throw exception error. I am assuming that the problem is on the google credential but not sure...
Could somebody help me out with this? I don't even know that the var credential = GoogleCredential.FromFile(Credential_Path); would be the right way to call the json file...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
var credential = GoogleCredential.FromFile(Credential_Path);
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
You just need to setup the environment variable GOOGLE_APPLICATION_CREDENTIALS as mentioned here
You mus have to mention you json file name in the environment variable as this.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
Your code would look like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
//var credential = GoogleCredential.FromFile(Credential_Path);
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
or you can send it through your Credential_Path variable.
for more details please visit Google Vision API Docs
You need to setup your environment in your console with code like this :
Windows Server:
$env:GOOGLE_APPLICATION_CREDENTIALS="File Path"
Linux Server :
export GOOGLE_APPLICATION_CREDENTIALS="File Path"
Hope it helps!
I am trying to use Stanford NLP for .NET. I am very new to this and I am having trouble in loading the models.
I have read the same kind of issue in https://sergey-tihon.github.io/Stanford.NLP.NET//faq.html and in Stanford.NLP for .NET not loading models. But I have no idea where they have saved the "stanford-corenlp-full-2016-10-31" folder.
This is where I have the C# code. C:\Users\Kabi\source\repos\Search\Search
And the stanford-corenlp-full-2017-06-09 folder is here - C:\Users\Kabi\source\repos\Search.
I have extracted the stanford-corenlp-3.8.0-models.jar in C:\Users\Kabi\source\repos\Search\stanford-corenlp-full-2017-06-09
This is my C# code.
Browse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using java.util;
using java.io;
using edu.stanford.nlp.pipeline;
using Console = System.Console;
namespace Search
{
class Browse
{
public void StanfordNLP()
{
// Path to the folder with models extracted from `stanford-corenlp-3.8.0-models.jar`
var jarRoot = #"..\stanford-corenlp-full-2017-06-09";
// Text for processing
var text = "Kosgi Santosh sent an email to Stanford University. He didn't get a reply.";
// Annotation pipeline configuration
var props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
props.setProperty("ner.useSUTime", "0");
// We should change current directory, so StanfordCoreNLP could find all the model files automatically
var curDir = Environment.CurrentDirectory;
Directory.SetCurrentDirectory(jarRoot);
var pipeline = new StanfordCoreNLP(props);
Directory.SetCurrentDirectory(curDir);
// Annotation
var annotation = new Annotation(text);
pipeline.annotate(annotation);
// Result - Pretty Print
using (var stream = new ByteArrayOutputStream())
{
pipeline.prettyPrint(annotation, new PrintWriter(stream));
Console.WriteLine(stream.toString());
stream.close();
}
}
}
}
How can I properly load the models?
It seems you are not able to locate your modals files try using this :-
I had copied stanford-corenlp-full-2017-06-09 under the root folder of my project i.e. NLP as displayed in image 1 in the picture itself the second one shows how I have extracted the stanford-corenlp-3.8.0-models.jar
The directory Structure of files
after doing so use
var jarRoot = #"......\stanford-corenlp-full-2016-10-31\stanford-corenlp-3.7.0-models";
It works Simply