C# File directory issue - c#

I have created a high score file for my game and I am having problems reading it.
When I change computers my USB drive changes letter .eg from drive E to drive G.
This is causing problems with reading the file. (as I use string path = #"g:\Scores.txt";)
So my question is.... can I set a default path to the program location??
My current code:-
string path = #"g:\Scores.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
any help is appreciated.

Is the game on your USB drive as well? Do you want to save the file in the same directory as the game, or in a directory somewhere around it? Do something like this:
using System;
using System.IO;
using System.Reflection;
...
string thisAsmFile = Assembly.GetExecutingAssembly().Location;
string thisAsmDir = Path.GetDirectoryName(thisAsmPath);
string highScoreFile = Path.Combine(thisAsmDir, "scores.txt");

If your program is in the same folder as the file ( Eg. in G:\ ), then you can simply access the file with his name : `path = "Scores.txt".
In that case there is no need to know where is the file

You should use your application path, not an absolute path.
You may do something like this:
using System.IO;
using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

Related

Invalid data found when processing input on ffmpeg m4s to mp4 transfer

The result of the power shell window
I saw a post on here about converting m4s to mp4 and I have followed the steps of concatenating all the files into another m4s file that I called all.m4s and when I use the command ffmpeg -i allm4s.m4s -c copy video.mp4. I made the combined m4s file by coding an exe to add all the m4s files that have the word video in them to the m4s file. Here is the source code written in c# if you compile the code then that is the code I have used to make the m4s
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace files
{
class Program
{
static void Main(string[] args)
{
string dir = Directory.GetCurrentDirectory();
string[] info = Directory.GetFiles(dir);
Console.WriteLine(dir + "\\allm4s.m4s");
Console.ReadKey();
foreach (string name in info)
{
if (Path.GetFileName(name).Contains(".m4s") && Path.GetFileName(name).Contains("video"))
{
using (Stream srcStream = File.OpenRead(name))
{
using (Stream destStream = File.OpenWrite(dir+"\\allm4s.m4s"))
{
srcStream.CopyTo(destStream);
Console.WriteLine(destStream+name);
}
}
}
}
Console.ReadKey();
}
}
}
I think if there is to be an issue it is to do with this allm4s.m4s file as the file size is about 1.5mb even though each segment m4s is about 750kb each and there are quite a lot.If anyone has a way of adding concatenating lots of files together through a program/application that would be useful.
You are getting that error because you might be concatenating videos of different dimensions.
all your input file's full names are stored in input array
Java Program
String inputStr="";
String stream="";
for(int index=0;index<input.length;index++){
inputStr=inputStr+" -i "+input[index];
stream =stream +"["+index+":v]"+"["+index+":a]"; //gets audio and video stream of file
}
String command = "ffmpeg "+inputStr+" -filter_complex \" "+stream+" concat=n="+(index-1)+ \
":v=1:a=1 [v] [a] \" "+ "-map \"[v]\" -map \"[a]\" outputfile.m4s"
Runtime.getRuntime(command).exec().waitFor();//runs ffmpeg command to concat all files

downloading the content of an xml file from Azure Blob Storage

In order to prevent the usual issues where I have an Xml file in a folder in one project and want to access it from other projects and have to deal with the file path issues, I want to download the Xml file contents directly from Azure blob storage where it resides now.
Not sure how to accomplish that although I see many examples of how to download images into streams, not sure how that works for Xml.
I am currently using the following ( which works until I move the Xml file)
public class MenuLoader
{
//var rootpath = HttpContext.Current.Server.MapPath("~");
private static readonly string NavMenuXmlPath = Path.Combine(ServicesHelpers.GetClassLibraryRootPath(),
#"ServicesDataFiles\MRNavigationMenu.xml");
);
//load the menus, based on the users role into the AppCache
public static void LoadMenus(IPrincipal principal)
{
var navXml = new NavigationMenusFromXml(NavMenuXmlPath);
var nmim = new NavigationMenuItemManager(navXml);
AppCache.Menus = nmim.Load(principal);
}
}
I want to eliminate all the bs associated with path combining and just download the xml from the file on Azure, i.e. replacing the string
#"ServicesDataFiles\MRNavigationMenu.xml"
with
"https://batlgroupimages.blob.core.windows.net:443/files/MRNavigationMenu.xml"
Naturally, that wouldn't work but there must be someway to load that xml into a file variable for use with the method.
Note: That is a publicly accessible file on azure for testing.
Use a memory stream. Remember to set position to zero before attempting to read.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
const string URL = "https://batlgroupimages.blob.core.windows.net/files/MRNavigationMenu.xml";
static void Main(string[] args)
{
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
XmlDocument doc = new XmlDocument();
doc.Load(URL);
writer.WriteRaw(doc.OuterXml.ToString());
writer.Flush();
}
}
}

Loop through Embedded Resources and copy to local path

I have a simple WinForms application, but it has some Embedded Resources (in a subfolder under "Resources") that I would like to copy out to a folder on the computer. Currently, I have the latter working (with a explicit method naming the Embedded Resource and where it should go):
string path = #"C:\Users\derek.antrican\";
using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream("WINFORMSAPP.Resources.SUBFOLDER.FILE.txt"))
using (Stream output = File.Create(path + "FILE.txt"))
{
input.CopyTo(output);
}
But I'm still trying to figure out how to get the former working: looping through all the resources in the "WINFORMSAPP.Resources.SUBFOLDER" folder and moving them. I've done quite a bit of Googling, but I'm still not sure how to get a list of each Embedded Resource in this subfolder.
Any help would be GREATLY appreciated!
Start by getting all resources embedded in your assembly:
Assembly.GetExecutingAssembly().GetManifestResourceNames()
You can check these names against the name of your desired subfolder to see if they are inside or outside it with a simple call to StartsWith.
Now loop through the names, and get the corresponding resource stream:
const string subfolder = "WINFORMSAPP.Resources.SUBFOLDER.";
var assembly = Assembly.GetExecutingAssembly();
foreach (var name in assembly.GetManifestResourceNames()) {
// Skip names outside of your desired subfolder
if (!name.StartsWith(subfolder)) {
continue;
}
using (Stream input = assembly.GetManifestResourceStream(name))
using (Stream output = File.Create(path + name.Substring(subfolder.Length))) {
input.CopyTo(output);
}
}

C#: Google Text-to-speech Loop

I'm creating a simple program that takes a string, sends it to Google's text to speech server, and downloads the text to speech in a mp3/wav file on the computer. I have the code below, but it only works with up to 100 characters (Google's limit). How can I make a loop to cut the string into 100 character parts and then save it in one mp3/wav file on the computer? I know this is possible with javascript and actionscript (as I have seen them) but how can I do this in C#?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
namespace TestCSharp
{
class Program
{
static void Main(string[] args)
{
WebClient web = new WebClient();
web.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 9.0; Windows;)");
string encstr = string.Empty;
string filename = "tts.mp3"; //could also be tts.wav
string s = "This string cannot be more than 100 characters.";
encstr = Uri.EscapeDataString(s);
Console.WriteLine(encstr);
web.DownloadFile("http://translate.google.com/translate_tts?tl=en&q=" + encstr, ".\\" + filename);
}
}
}
This is not a direct answer, but I think the splitting is not good because TTS has word intonation as well as sentence intonation. Instead, I recommend you use SpeechSynthesizer Class with free TTS engine. However, I don't know which TTS engine is good as free and where it is. If finding goodness, I'll post it.
UPDATED
MP3 files are just concatenated without a problem, from this question.
well, before I get to concatenating the mp3 files, how would the while
loop look like to first get those mp3 files on the computer? if i go
through my loop, the tts.mp3 file would be overwritten and i would be
left with only the last 100 character string that was received..
You can merge the two files like the code below.
Finally, the fs1 will get all content.
string tts1 = "tts1.mp3";
string tts2 = "tts2.mp3";
FileStream fs1 = null;
FileStream fs2 = null;
try
{
fs1 = File.Open(tts1, FileMode.Append);
fs2 = File.Open(tts2, FileMode.Open);
byte[] fs2Content = new byte[fs2.Length];
fs2.Read(fs2Content, 0, (int)fs2.Length);
fs1.Write(fs2Content, 0, (int)fs2.Length);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " : " + ex.StackTrace);
}
finally
{
fs1.Close();
fs2.Close();
}

How to fix System.UnauthorizedAccessException when decompressing bz2 file?

Im trying to decompress a bz2 file via code using the ICSharpCode.SharpZipLib.
It seems no matter where I make my file, even though I have FULL ACCESS control over it, I keep getting this Exception. Any help greatly appreciated.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
namespace decompressor
{
class MainClass
{
public static void Main(string[] args)
{
string filePath = "C:\\FreeBase\\opinions.tsv.bz2";
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed";
Console.WriteLine("Decompressing {0} to {1}", file, path);
BZip2.Decompress(File.OpenRead(filePath),File.OpenWrite(decompressPath), true);
}
}
}
Your code can have no access to create new paths at your desktop.
Check the permissions for the "C:\\Users\\mike\\Desktop\\Decompressed".
Maybe, you should write so:
string decompressPath = "C:\\Users\\mike\\Desktop\\Decompressed\\opinions.tsv";

Categories