I have list of MP3 files that I would like to merge them into one file. I downloaded files locally into isolated storage, but I have no idea how to merge them. Google doesn't help either. I don't know if its possible in WP8. (2) If not possible what specific solution you could advice (I also have my files in web).
I write below code for merging, but this always writes the last file.
string[] files = new string[] { "001000.mp3", "001001.mp3", "001002.mp3", "001003.mp3", "001004.mp3", "001005.mp3", "001006.mp3", "001007.mp3" };
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string newFileName = "001.mp3";
foreach (string _fileName in files)
{
if (storage.FileExists(_fileName))
{
byte[] bytes = new byte[1];
using (var f = new IsolatedStorageFileStream(_fileName, FileMode.Open, storage))
{
bytes = new byte[f.Length];
int byteCount;
using (var isfs = new IsolatedStorageFileStream(newFileName, FileMode.OpenOrCreate, storage))
{
while ((byteCount = f.Read(bytes, 0, bytes.Length)) > 0)
{
isfs.Write(bytes, 0, byteCount);
isfs.Flush();
}
}
}
}
}
}
How can i add (merge) files to end of the newly created file?
I added isfs.Seek(0, SeekOrigin.End); before writing to file. This is how we can simply merge same bitrate mp3 files.
the code looks like below:
using (var isfs = new IsolatedStorageFileStream(newFileName, FileMode.OpenOrCreate, storage))
{
isfs.Seek(0, SeekOrigin.End); //THIS LINE DID SOLVE MY PROBLEM
while ((byteCount = f.Read(bytes, 0, bytes.Length)) > 0)
{
isfs.Write(bytes, 0, byteCount);
isfs.Flush();
}
}
Please improve my code if it seems to be longer.
Related
So currently I got a text file in a shared folder on my PC and I want to access it from android Phone.
Here is the code I'm using but it's not finding the file.
void ReadFile()
{
TextView file = FindViewById<TextView>(Resource.Id.fileview);
string filepath = #"\\192.168.8.102\Sharedtest\test.txt";
if (!File.Exists(filepath))
{
file.Text = "No File Found";
}
else
{
foreach (string line in File.ReadLines(filepath, Encoding.UTF8))
{
file.Text = $"{line}\n";
}
}
}
File is shared and no firewall.
If someone can just point me in a direction that would be great.
I don't want to download file I just want to read content.
You can use FileStream with FileMode.Open. check Microsoft doc.
using (FileStream fs = File.Open(path, FileMode.Open))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
file.Text = temp.GetString(b);
}
}
I am following Amazon's tutorial on S3 but I cannot download file and save it to Streaming Resources. Instead I am downloading file content.
ResultText.text = string.Format("fetching {0} from bucket {1}", SampleFileName, S3BucketName);
Client.GetObjectAsync(S3BucketName, SampleFileName, (responseObj) =>
{
string data = null;
var response = responseObj.Response;
if (response.ResponseStream != null)
{
using (StreamReader reader = new StreamReader(response.ResponseStream))
{
data = reader.ReadToEnd();
}
ResultText.text += "\n";
ResultText.text += data;
}
});
I understand that I should convert the response.ResponseStream into File but I tried many different solutions and I could not make it working.
I understand that I should convert the response.ResponseStream into File but ....
You do not convert it into a file you read from it and write the content to a file. There are plenty of built in methods that help with this but the steps are simple. Open/Create a file stream and then write from the response stream to the file stream.
if (response.ResponseStream != null)
{
using (var fs = System.IO.File.Create(#"c:\some-folder\file-name.ext"))
{
byte[] buffer = new byte[81920];
int count;
while ((count = response.ResponseStream.Read(buffer, 0, buffer.Length)) != 0)
fs.Write(buffer, 0, count);
fs.Flush();
}
}
My company run an application that have to archive many kinds of files into some distants servers. The application works well but can't handle files larger than 1GB.
Here is the current function use to load the files to be uploaded to the distant server :
FileStream fs = File.OpenRead(fileToUploadPath);
byte[] fileArray = new byte[fs.Length];
fs.Read(fileArray, 0, fs.Length);
The byte array (when loaded successfully) was then splited into 100Mb bytes arrays and sent to the local server (using some WSDL web services) with the following function :
localServerWebService.SendData(subFileArray, filename);
I changed the function responsible for the file reading to use BufferendStream and I also wanted to improve the Webservice part so that it doesn't have to create a new stream at each call. I thought of somethings like this :
FileInfo source = new FileInfo(fileName);
using (FileStream reader = File.OpenRead(fileName))
{
using (FileStream distantWriter = localServerWebService.CreateWriteFileStream(fileName))
{
using (BufferedStream buffReader = new BufferedStream(reader))
{
using (BufferedStream buffWriter = new BufferedStream(distantWriter))
{
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = 0;
long bytesToRead = source.Length;
while (bytesToRead > 0)
{
int nbBytesRead = buffReader.Read(buffer, 0, buffer.Length);
buffWriter.Write(buffer, 0, nbBytesRead);
bytesRead += nbBytesRead;
bytesToRead -= nbBytesRead;
}
}
}
}
}
But this code can't compile and always give me the error Cannot convert MyNameSpace.FileStream into System.IO.FileStream at line using (FileStream distantWriter = localServerWebService.CreateWriteFileStream(fileName)). I can't cast MyNameSpace.FileStream into System.IO.FileStream either.
The web service method :
[WebMethod]
public FileStream CreateWriteFileStream(String fileName)
{
String RepVaultUP =
System.Configuration.ConfigurationSettings.AppSettings.Get("SAS_Upload");
String desFile = Path.Combine(RepVaultUP, fileName);
return File.Open(desFile, FileMode.Create, FileAccess.Write);
}
So can you guys please explain to me why is this not working?
P.S.: English is not my mothertong so I hope what i wrote is clearly undestandable.
Inside my app, I am trying to download about 180 small audio files all at once. I tried the BackgroundTransferService, but it does not seem stable with so many small files. So, now I am downloading a ZIP of all those audio and want extract them in "audio" folder. I tried the method in this thread:
How to unzip files in Windows Phone 8
But I get this error: 'System.IO.IOException' occurred in mscorlib.ni.dll... in the following code. How can I overcome this issue?
while (reader.ReadInt32() != 101010256)
{
reader.BaseStream.Seek(-5, SeekOrigin.Current); // this line causes error
}...
Also, where do I need to place this code and where do I give it the destination directory?
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"audio.rar", FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip())
{
string FileName = filename;
}
}
Use Silverlight SharpZipLib. Add SharpZipLib.WindowsPhone7.dll to your project (works on WP8 silverlight also).
private void Unzip()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
ZipEntry entry;
int size;
byte[] data = new byte[2048];
using (ZipInputStream zip = new ZipInputStream(store.OpenFile("YourZipFile.zip", FileMode.Open)))
{
// retrieve each file/folder
while ((entry = zip.GetNextEntry()) != null)
{
if (!entry.IsFile)
continue;
// if file name is music/rock/new.mp3, we need only new.mp3
// also you must make sure file name doesn't have unsupported chars like /,\,etc.
int index = entry.Name.LastIndexOf('/');
string name = entry.Name.Substring(index + 1);
// create file in isolated storage
using (var writer = store.OpenFile(name, FileMode.Create))
{
while (true)
{
size = zip.Read(data, 0, data.Length);
if (size > 0)
writer.Write(data, 0, size);
else
break;
}
}
}
}
}
}
There are several 3rd party libraries in order to extract ZIP files in WP8 like the ZipLib which you can download from # http://slsharpziplib.codeplex.com/
however DotNetZip a parent ZipLib and much more stable.
Here is a sample code. Not checked if it works, but this is how you go at it.
ZipFile zip = ZipFile.Read(ZipFileToUnzip);
foreach (ZipEntry ent in zip)
{
ent.Extract(DirectoryWhereToUnizp, ExtractExistingFileAction.OverwriteSilently);
}
I have just solved this. what you can do is use this method and your file will go save to isolated storage in proper folder structure as present in your zip file. you can change according to your need where you want to store the data.
I have just read a sample.zip file. From your app folder.
private async Task UnZipFile()
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
cheers :)
Whats the best way to zip up files using C#? Ideally I want to be able to seperate files into a single archive.
You can use DotNetZip to archieve this. It´s free to use in any application.
Here´s some sample code:
try
{
// for easy disposal
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: " + ex1);
}
This is now built into the framework if you have version 4.5+
Otherwise, use Ionic.
Namespace is System.IO.Packaging.ZIPPackage.
See http://visualstudiomagazine.com/articles/2012/05/21/net-framework-gets-zip.aspx for a story.
Have you looked at SharpZipLib?
I believe you can build zip files with classes in the System.IO.Packaging namespace - but every time I've tried to look into it, I've found it rather confusing...
Take a look at this library:
http://www.icsharpcode.net/OpenSource/SharpZipLib/
It is pretty comprehensive, it deals with many formats, is open-source, and you can use in closed-source commercial applications.
It is very simple to use:
byte[] data1 = new byte[...];
byte[] data2 = new byte[...];
/*...*/
var path = #"c:\test.zip";
var zip = new ZipOutputStream(new FileStream(path, FileMode.Create))
{
IsStreamOwner = true
}
zip.PutNextEntry("File1.txt");
zip.Write(data1, 0, data1.Length);
zip.PutNextEntry("File2.txt");
zip.Write(data2, 0, data2.Length);
zip.Close();
zip.Dispose();
There are a few librarys around - the most popular of which are DotNetZip and SharpZipLib.
Hi i created two methods with the ShapLib library (you can download it here http://www.icsharpcode.net/opensource/sharpziplib/) that would like to share, they are very easy to use just pass source and target path (fullpath including folder/file and extension). Hope it help you!
//ALLYOURNAMESPACESHERE
using ...
//SHARPLIB
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
public static class FileUtils
{
/// <summary>
///
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
public static void ZipFile(string sourcePath, string targetPath)
{
string tempZipFilePath = targetPath;
using (FileStream tempFileStream = File.Create(tempZipFilePath, 1024))
{
using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
{
// Zip with highest compression.
zipOutput.SetLevel(9);
DirectoryInfo directory = new DirectoryInfo(sourcePath);
foreach (System.IO.FileInfo file in directory.GetFiles())
{
// Get local path and create stream to it.
String localFilename = file.FullName;
//ignore directories or folders
//ignore Thumbs.db file since this probably will throw an exception
//another process could be using it. e.g: Explorer.exe windows process
if (!file.Name.Contains("Thumbs") && !Directory.Exists(localFilename))
{
using (FileStream fileStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Read full stream to in-memory buffer.
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
// Create a new entry for the current file.
ZipEntry entry = new ZipEntry(file.Name);
entry.DateTime = DateTime.Now;
// set Size and the crc, because the information
// about the size and crc should be stored in the header
// if it is not set it is automatically written in the footer.
// (in this case size == crc == -1 in the header)
// Some ZIP programs have problems with zip files that don't store
// the size and crc in the header.
entry.Size = fileStream.Length;
fileStream.Close();
// Update entry and write to zip stream.
zipOutput.PutNextEntry(entry);
zipOutput.Write(buffer, 0, buffer.Length);
// Get rid of the buffer, because this
// is a huge impact on the memory usage.
buffer = null;
}
}
}
// Finalize the zip output.
zipOutput.Finish();
// Flushes the create and close.
zipOutput.Flush();
zipOutput.Close();
}
}
}
public static void unZipFile(string sourcePath, string targetPath)
{
if (!Directory.Exists(targetPath))
Directory.CreateDirectory(targetPath);
using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.Name != String.Empty)
{
using (FileStream streamWriter = File.Create(targetPath + "\\" + theEntry.Name))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
}