So I have an upload file button which opens an open file dialog and lets you select a file.
Im not connected to server or db yet so just trying to send selected files to a specific folder on my c: drive, once the file is used it will be deleted so the name of the file will always be different.
when i want to send the file path to the method that will be using it is there a way to specify just the folder its in and for the system to use the only file within that folder then.
So far my code is all over the place as ive been trying to play around with it as im new to c# but this is what its lie so far(obviously the var isnt working and sch tried to use another example I found, getting 'not all code paths return a value error for 'getVideoFile'):
public static string getVideoFile (string filePath)
{
var path= string;
path = Directory.GetFiles(#"C:\Users\siobhan\Videos\FYPVids\");
if (path != 0){
return path;
}
else
{
//put in error message for no video file detected
}
}
the button itself:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (this.btnFileUpload.HasFile)
{
this.btnFileUpload.SaveAs(#"C:\Users\siobhan\Videos\FYPVids" + this.btnFileUpload.FileName);
}
The method the file path needs to be sent to:
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = vidDetails.vidTitle;
video.Snippet.Description = vidDetails.vidDesc;
video.Snippet.Tags = new string[] { "Test", "Second" };
video.Snippet.CategoryId = "17";//category id for sport // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Snippet.ChannelId = "UCfvR-wqeoHmAGrHnoQRfs9w";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; /2015\WebSites\FYP_November\IMG_6639.mp4"; // Replace with path to actual movie file.
Related
So, I have this code i am programming under a button. When pressed, the user is asked if they want to download the newest File. If yes, then download it and the download location is supposed to be: Documents\Fiddler2 (You Get this Folder created when Installing Fiddler Classic).
However, after several different attempts, the file is only downloaded to the Documents Folder and needs to download to the Documents\Fiddler2 Folder. What am I doing wrong?
private void button4_Click(object sender, EventArgs e)
{
string title = "Check For New Version.";
string question = "Would you like to Check for any Updates?";
string url = "www.google.com";
if (DialogResult.Yes ==
MessageBox.Show(this, question, title,MessageBoxButtons.YesNo,MessageBoxIcon.Question))
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string path2 = Path.Combine(path, #"Fiddler2");
MessageBox.Show(path2);
Directory.SetCurrentDirectory(path2);
using (var client = new WebClient())
{
client.DownloadFile("https://drive.google.com/file/d/13K2IEH-FNQ2HhqAlvaYO3sEZoeWOtPMN/view?usp=sharing", "test.png");
}
}
I am new to Xamarin. I have simple app; Where I have notes field and take picture functionality. I am using media plugin to take pictures. The picture obviously get saved in phone gallery.
But I also wanted to save the text file which contains the input from notes field in phone.
I am struggling to save the text file.
The is the product structure. I am using shared project.
File structure and classes image
Sample app image
I have an save button. What I want to do is when save button is clicked; save the text file which has user input from notes field.
Here is action of my save button
I was looking on this website
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=windows
I tried some code but nothing worked.
private async void Take_Photo_Button_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
SaveToAlbum = true,
Name = jobnoentry.Text + "-" + Applicationletterentry + "-" + signnoentry.Text + "-" + SignType,
});
if (file == null)
return;
MainImage.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
return stream;
});
//Save text field
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
File.WriteAllText(fileName, "Hello World");
}
First, where exactly a file gets saved depends on the platform, but you can always print the string for the filename to see the actual path, e.g.
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
Console.WriteLine(filename); // will write the actual path to the application output.
In any case the path you are using, Environment.SpecialFolder.LocalApplicationData, will save the text file to a location only accessible by the app itself, you won't see it in a file browser. If you need to have the text files available outside of your app, how to do that will vary based on platform and you will need to use a dependency service to get the correct file paths.
However you can verify if you have saved and can read a file as follows:
string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "temp.txt");
File.WriteAllText(fileName, "Hello World");
The above is code from your post. If you don't get an exception, chances are it worked. To verify:
var text = File.ReadAllText(filename);
if (text == "Hello World")
Console.WriteLine("File contents verified and correct");
else
Console.WriteLine("File contents do not match saved string");
I want to upload an image to a specific folder and if that folder does not exist create it and make this folder shareable to another email address.
I use the below code:
MetadataChangeSet changeSetfile = new MetadataChangeSet.Builder()
.SetTitle("Test.jpg")
.SetMimeType("image/jpeg")
.Build();
MetadataChangeSet changeSetfolder = new MetadataChangeSet.Builder()
.SetTitle("New folder")
.SetMimeType(DriveFolder.MimeType)
.SetStarred(true)
.Build();
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFolder(_googleApiClient, changeSetfile) ;
DriveClass.DriveApi
.GetRootFolder(_googleApiClient)
.CreateFile(_googleApiClient, changeSetfolder, contentResults.DriveContents);
First, you have to check if the folder exist. According to this tutorial - Search files on Google Drive with C#, you can use:
By file name
What if you know the name of the file or part of the name well you can search on name. Fulltext is also nice it allows you to search on “Full text of the file including name, description, content, and indexable text.”
List files only directories
It is also possible to search for only one type of file say you just want to return all the Google sheets on your account? What if you just wanted to find all the folders well folders is a mimetype of “application/vnd.google-apps.folder” so we can search on just that.
Upon check if it is existing, get the ID to be place in the parents parameter:
var folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
var fileMetadata = new File()
{
Name = "photo.jpg",
Parents = new List<string>
{
folderId
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("files/photo.jpg",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
Hope this helps.
I'm pretty new to processing recorded sound.
I can successfully record audio into a .3gpp file, save it locally on my mobile device, and play it back.
The trouble I'm having is that I want to convert the sound file into binary so that I can stick it into a parseObject, and upload the file to a cloud. I then want to be able to access that file from a separate device, and stream it.
--UPDATE--- I'm not using binary anymore, I'm using a parseFile object. I now just need to pull the object down from the cloud.
Here's the code I'm using to record the audio (working):
string sName;
string path = "/storage/extSdCard/";
string newPath = "";
_start.Click += delegate {
_stop.Enabled = !_stop.Enabled;
_start.Enabled = !_start.Enabled;
sName = _edittext.Text;
if (sName.Equals(" "))
{
}
else
{
//user enters a name for ther audio file
newPath = path + sName + ".3gpp";
_recorder.SetAudioSource (AudioSource.Mic);
_recorder.SetOutputFormat (OutputFormat.ThreeGpp);
_recorder.SetAudioEncoder (AudioEncoder.AmrNb);
_recorder.SetOutputFile (newPath);
_recorder.Prepare ();
_recorder.Start ();
}
};
_stop.Click += delegate {
_stop.Enabled = !_stop.Enabled;
_recorder.Stop ();
// _recorder.Reset ();
_player.SetDataSource (newPath);
_player.Prepare ();
_player.Start ();
};
Here is the class I'm using to send the data to a cloud - this is executed on the click of a button and works, it currently sends hard coded strings into an object which i can successfully retrieve.
HOWEVER, I want the binary string to go into the testObject["audio"], so I can retrieve it.
async Task sendToCloud()
{
ParseClient.Initialize ("--I've put my keys here but I'm censoring them--", "--I've put my keys here but I'm censoring them--");
try
{
byte[] data =null;
ParseFile file = null;
using (StreamReader reader = new StreamReader(LoadPath))
{
data = System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd());
file = new ParseFile("theaudio.3gpp", data);
}
Console.WriteLine("Awaiting reader");
await file.SaveAsync ();
var auidoParseObject = new ParseObject("AudioWithData");
//Console.WriteLine(ParseUser.getUserName());
auidoParseObject["userName"] = "userName";
auidoParseObject["file"] = file;
await auidoParseObject.SaveAsync();
}
Any help would be GREATLY APPRECIATED.
EDIT2:
I've made some progress, I'm struggling, however, to get the audio file down from the cloud still.
here's my new code:
async Task sendToCloud(string filename)
{
ParseClient.Initialize ("censored", "censored");
var testObject = new ParseObject ("Audio");
string LoadPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
string savetheFile = sName + ".3gpp";
string tempUserName;
LoadPath += savetheFile;
Console.WriteLine ("loadPath: " + LoadPath);
try
{
byte[] data = File.ReadAllBytes(LoadPath);
ParseFile file = new ParseFile(savetheFile, data);
await file.SaveAsync();
var auidoParseObject = new ParseObject("AudioWithData");
//Console.WriteLine(ParseUser.getUserName());
if (ParseUser.CurrentUser != null)
{
tempUserName = ParseUser.CurrentUser.Username.ToString();
}
else{
tempUserName = "Anonymous";
}
//tempUserName = ParseUser.CurrentUser.Username.ToString();
Console.WriteLine("PARSE USERNAME: " + tempUserName);
auidoParseObject["userName"] = tempUserName;
auidoParseObject["userName"] = tempUserName;
auidoParseObject["file"] = file;
await auidoParseObject.SaveAsync();
}
catch (Exception e)
{
Console.WriteLine("Failed to await audio object! {0}" + e);
}
}
So currently, my objects have the following structure:
"auidoParseObject" contains two children: username (string) and file (ParseFile object)
"file" has two children: the name of the audio (entered by the user -string), and the data in bytes.
I need the audio to be placed into a mdeiaplayer player object, and played.
In the long run, I'll want to extract:
(forgive my pseudo-SQL, but I don't understand the querying documentation):
Select (all files) from (audioParseObject) where (the username = current user.username)
AND THEN
put those files into a listview
user selects a file from the listview and it plays.
ANY help or pointers would be great.
Thanks.
Parse has really good docs on their site with examples - have you read them?
First, you would use a ParseFile (not a ParseObject) to save your file
byte[] data = File.ReadAllBytes(path_to_your_file);
ParseFile file = new ParseFile("your_file_name_and_ext", data);
await file.SaveAsync();
After you save your file, you can add a reference to it in your ParseObject
testObject ["audio"] = file;
To retrieve the file later, you use the Url property from the ParseFile.
var file = testObject.Get<ParseFile>("audio");
byte[] data = await new HttpClient().GetByteArrayAsync(file.Url);
I've got a C# file upload that is meant to extract XML tags from inside a DocX document, the problem I'm facing is that when the file is uploaded, the error "File is being used by another process" comes up. Attempting to delete the document shows it is being used by IIS process manager.
Is there a way to stop my code to get it to continue running?
<script runat="server">
//foreach (DataRow row in table.Rows)
//{
// string dbColumnNames = (selectedData.ToString());
//send files
//}
public string _TempFileLocation = ""; //Used to locate Word Document File Path
//THE USER UPLOAD CONTROL. users use this to upload the document to the server
public void XMLextractor(string _filePath)
{
//XML extraction code
displayFilepath.Text = _filePath;
_TempFileLocation = _filePath;
}
//names the script manager which will be used when the user attempts to upload a form / gives an error if they incorrectly attempt to upload
protected void UploadButton_Click(object sender, EventArgs e)
{
//if file is located
if (FileUploadControl.HasFile)
{
try
{
//allow content type of document / docx
if (FileUploadControl.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
{
if (FileUploadControl.PostedFile.ContentLength < 10485760) // 10mb)
{
//name the filename, find the path of the name
string filename = Path.GetFileName(FileUploadControl.FileName);
//path of server upload (we just need to save it as a variable to be found on the next page, as it will be made / deleted
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
//update the label with file uploaded
StatusLabel.Text = "Upload status: File uploaded!";
XMLextractor(Server.MapPath("~/") + filename);
//move onto template wizard page
//Response.Redirect("http://portal.acoura.com/admin/templatewizard.aspx", false);
WordprocessingDocument _TempDoc = WordprocessingDocument.Open(Server.MapPath("~/") + filename, true);
XDocument xdoc = XDocument.Load(Server.MapPath("~/") + filename);
//query to find particular descendants
var lv1s = from document in xdoc.Descendants("table")
select new
{
Header = document.Attribute("name").Value,
Children = document.Descendants("tag")
};
//Loop through results
StringBuilder result = new StringBuilder();
foreach (var lv1 in lv1s)
{
result.AppendLine(lv1.Header);
foreach (var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
//the label should contain the content controls of the document, using the class, XMLfromDocument
labelContentControls.Text = fileUpload_Displayx(XMLfromDocument.GetContentControls(_TempDoc));
}
else
//display the size the file needs to be less than
StatusLabel.Text = "Upload status: The file has to be less than 10mb!";
}
else
//tell the user only docx files are accepted
StatusLabel.Text = "Upload status: Only DOCX files are accepted!";
}
catch (Exception ex)
{
//display the exception message, in which case it would be either size / type / if it's present
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
//needs to be replaced with the variable found in descendants / var tagContent
public string fileUpload_Displayx(XElement _contentcontrol)
{
string str = "";
str = _contentcontrol.Name.ToString();
return str;
}
//public static displayDatabase(object sender, EventArgs e)
// {
//}
//run the validate button on templatewizard, will mark up any problems or give green light
//if red, allow users to replace fields in the left column, from ones in the atabase on the right
//display upload button when validation is succesful. When Upload button runs, Take to new
// / existing page of reports, allow users to download this
</script>
You are opening the file without closing it on this line:
WordprocessingDocument _TempDoc = WordprocessingDocument.Open(Server.MapPath("~/") + filename, true);
Then you are opening it again with xDocument.Load():
XDocument xdoc = XDocument.Load(Server.MapPath("~/") + filename);
I assume that is where the error occurs.
If you handle all of the stuff XDocument needs to do first, and then open and close the WordProcessingDocument.Open() line to get the content controls, you should be fine.
Basically only one process can have a open and read or modify a file at a time, so if two operations from two different sources need to be performed, they must be performed sequentially on the file.
You can also open the file via a FileStream and then load the content into memory and into your XDocument, therefore negating the need to have the file opened twice by XDocument and WordProcessingDocument simultaneously.
Hope this helps!