I created a little game with the option to save the character into an XML File, now I wanted the Savegame-Folder location to be at MyDocuments, but every time I try to save the XML I just get an access denied from my streamwriter. Does someone know how to fix that?
Here's my code:
// Create the folder into MyDocuments (works perfectly!)
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"Arena\Savegames\"));
// This one should the save the file into the directory, but it doesn't work :/
path = Path.GetDirectoryName(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Arena\Savegames\" + hero.created + ".xml"));
The Streamwriter:
public class SaveLoadGame
{
public void SaveGameData(object IClass, string filename)
{
StreamWriter saveGameWriter = null;
try
{
XmlSerializer saveGameSerializer = new XmlSerializer((IClass.GetType()));
saveGameWriter = new StreamWriter(filename);
saveGameSerializer.Serialize(saveGameWriter, IClass);
}
finally
{
if (saveGameWriter != null)
saveGameWriter.Close();
saveGameWriter = null;
}
}
}
public class LoadGameData<T>
{
public static Type type;
public LoadGameData()
{
type = typeof(T);
}
public T LoadData(string filename)
{
T result;
XmlSerializer loadGameSerializer = new XmlSerializer(type);
FileStream dataFilestream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
result = (T)loadGameSerializer.Deserialize(dataFilestream);
dataFilestream.Close();
return result;
}
catch
{
dataFilestream.Close();
return default(T);
}
}
}
I tried some of the solutions I found here on stackoverflow like this and this. But didn't work for me, maybe someone else has an idea how I can get access to that folder? Or maybe just save it somewhere I actually have access, because ApplicationData and CommonApplicationData didn't work for me either.
Btw I'm using Virtual Box with Win10_Preview, I hope it's not because of this.
Edit: Before trying to save the files to MyDirectory I managed to save the files into my Debug folder of the project like this:
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\Savegames\" + hero.created + ".xml";
gameSaver.SaveGameData(myCharacterObject, path);
Thanks to Jon Skeet I figured out that I was just using the directory name, instead of the full path to save my file. So I just fixed the code to this:
// Creating the folder in MyDocuments
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"Arena\Savegames\"));
// Setting the full path for my streamwriter
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Arena\Savegames\" + hero.created + ".xml";
Related
I tried 'using' but it says that the method is not Idisposable. I checked for running processes in Task Manager, nothing there. My goal is to upload a file from local directory to the Rich Text editor in my website. Please help me resolve this issue. Thanks in Advance
public void OnPostUploadDocument()
{
var projectRootPath = Path.Combine(_hostingEnvironment.ContentRootPath, "UploadedDocuments");
var filePath = Path.Combine(projectRootPath, UploadedDocument.FileName);
UploadedDocument.CopyTo(new FileStream(filePath, FileMode.Create));
// Retain the path of uploaded document between sessions.
UploadedDocumentPath = filePath;
ShowDocumentContentInTextEditor();
}
private void ShowDocumentContentInTextEditor()
{
WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
Editor editor = new Editor(UploadedDocumentPath, delegate { return loadOptions; }); //passing path and load options (via delegate) to the constructor
EditableDocument document = editor.Edit(new WordProcessingEditOptions()); //opening document for editing with format-specific edit options
DocumentContent = document.GetBodyContent(); //document.GetContent();
Console.WriteLine("HTMLContent: " + DocumentContent);
//string embeddedHtmlContent = document.GetEmbeddedHtml();```
//Console.WriteLine("EmbeddedHTMLContent: " + embeddedHtmlContent);
}
FileStream is disposable, so you can use using on it:
using (var stream = new FileStream(filePath, FileMode.Create)
{
UploadedDocument.CopyTo(stream);
}
I have a Save ActionResult in my Controller that is set up to use StreamWriter. The code works perfectly, for saving to a file that exists.
Save Action
[HttpPost]
[ValidateInput(false)]
public ActionResult Save(string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
using (StreamWriter outputFile = new StreamWriter(Path.Combine(helper, filename)))
{
outputFile.WriteLine(lines);
return View();
}
}
I am now working on a file creation and from what i have read you can do this with StreamWriter although when I try to implement it, it says it cannot be found. Which tells me it is looking for a file instead of creating it.
So I tried to implement this using FileInfo. It appears that it has everything it needs but just doesn't save it. Below is my latest code. It does not like the
fs.Write(lines);
I had a try catch block. on this and it had the same results. That it cannot find it.
[HttpPost]
[ValidateInput(false)]
public ActionResult Create (string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
var file = "Test\\" + filename;
var pathString = System.IO.Path.Combine(helper, "Test\\", filename);
FileInfo fi = new FileInfo(pathString);
if (fi.Exists)
{
fi.Delete();
}
using (FileStream fs = fi.Create())
{
fs.Write(lines);
return View();
}
}
Thanks for your help!
Update:
This is the message I get. Below the message I have the actual string to the directory copied from folder explorer..
Exception thrown: 'System.IO.DirectoryNotFoundException' in mscorlib.dll
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code
Could not find a part of the path 'C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuider\Test\Test2.html'.
C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuilder\Test
Update:
I need to look at my code better! This is fixed.. The code at the very top works perfectly for both save and create. The problem was in the javascript code variables that i was feeding it. A Typo... If you look at the above comparison, which I did not catch myself, too many long nights I suppose, HMIBuilder is spelled HMIBuider... in the error.
using (StreamWriter outputFile = new StreamWriter(Path.Combine(path, "filename.txt")))
would create a new file, if needed.
Your problem may be the Test directory and CreateDirectory is here to help.
DirectoryInfo di = Directory.CreateDirectory(path);
If we put the writing to the file and creating directories together it could look like the following snippet.
var path = "./MyFiles/SpecialFiles";
var filename = "thisIsAVerySpecialFile.txt";
Directory.CreateDirectory(path);
//Create a new file or overwrite existing (i.e. *not* append)
using (var f = new StreamWriter(Path.Combine(path, filename)))
{
f.WriteLine("Hello world!");
}
Without Directory.CreateDirectory the code results in System.IO.DirectoryNotFoundException with 'Could not find a part of the path '(...)'.
I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}
I have a folder called data/ in my project that contains txt files.
I configured Build Action to resources to all files.
I tried these different ways:
method 1
var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());
method 2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");
method 3
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
{
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
al.Add(line);
Debug.WriteLine(line);
}
}
}
Now, i tried different ways to read files without success, why?
Where is the problem?
What's wrong with these methods?
fName is the name of the file.
It's necessary the full path data/filename.txt? It's indifferent...
please help me with this stupid issue,
thanks.
Your 2nd & 3rd approaches are wrong. When you include a text file locally in your app, you can't refer it via the IS. Instead, use this function, it will return the file content if found else it will return "null". It works for me, hope it works for you.
Note, if the file is set as content, the filePath = "data/filename.txt" but if it is set as resource it should be referred like this filePath = "/ProjectName;component/data/filename.txt". That may be why your 1st approach might have failed.
private string ReadFile(string filePath)
{
//this verse is loaded for the first time so fill it from the text file
var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
//read the content here
return myStreamReader.ReadToEnd();
}
}
return "NULL";
}
I want to zip one "CSV" file in to Zip file using C#.Net. Below i have written some code for create Zip file , using this code i am able to create zip file but after creating "Data1.zip" file extract manually means extracted file extension should be ".csv" but it is not coming.
FileStream sourceFile = File.OpenRead(#"C:\Users\Rav\Desktop\rData1.csv");
FileStream destFile = File.Create(#"C:\Users\Rav\Desktop\Data1.zip");
GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress,false);
try
{
int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = sourceFile.ReadByte();
}
}
finally
{
compStream.Dispose();
}
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
This is gzip compression, and apparently it only compresses a stream, which when decompressed takes the name of the archive without the .gz extension. I don't know if I'm right here though. You might as well experiment with the code from MSDN, see if it works.
I used ZipLib for zip compression. It also supports Bz2, which is a good compression algorithm.
Use ICSharpCode.SharpZipLib(you can download it) and do the following
private void CreateZipFile(string l_sFolderToZip)
{
FastZip z = new FastZip();
z.CreateEmptyDirectories = true;
z.CreateZip(l_sFolderToZip + ".zip", l_sFolderToZip, true, "");
if (Directory.Exists(l_sFolderToZip))
Directory.Delete(l_sFolderToZip, true);
}
private void ExtractFromZip(string l_sFolderToExtract)
{
string l_sZipPath ="ur folder path" + ".zip";
string l_sDestPath = "ur location" + l_sFolderToExtract;
FastZip z = new FastZip();
z.CreateEmptyDirectories = true;
z.ExtractZip(l_sZipPath, l_sDestPath, "");
if (File.Exists(l_sZipPath))
File.Delete(l_sZipPath);
}
Hope it helps...
Use one of these libraries:
http://www.icsharpcode.net/opensource/sharpziplib/
http://dotnetzip.codeplex.com/
I prefer #ziplib, but both are well documented and widely spread.
Since .NET Framework 4.5, you can use the built-in ZipFile class (In the System.IO.Compression namespace).
public void ZipFiles(string[] filePaths, string zipFilePath)
{
ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create);
foreach (string file in filePaths)
{
zipArchive.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
}
zipArchive.Dispose();
}
Take a look at the FileSelectionManager library here: www.fileselectionmanager.com
First you have to add File Selection Manager DLL to your project
Here is an example for zipping:
class Program
{
static void Main(string[] args)
{
String directory = #"C:\images";
String destinationDiretory = #"c:\zip_files";
String zipFileName = "container.zip";
Boolean recursive = true;
Boolean overWrite = true;
String condition = "Name Contains \"uni\"";
FSM FSManager = new FSM();
/* creates zipped file containing selected files */
FSManager.Zip(directory,recursive,condition,destinationDirectory,zipFileName,overWrite);
Console.WriteLine("Involved Files: {0} - Affected Files: {1} ",
FSManager.InvolvedFiles,
FSManager.AffectedFiles);
foreach(FileInfo file in FSManager.SelectedFiles)
{
Console.WriteLine("{0} - {1} - {2} - {3} - {4} Bytes",
file.DirectoryName,
file.Name,
file.Extension,
file.CreationTime,
file.Length);
}
}
}
Here is an example for unzipping:
class Program
{
static void Main(string[] args)
{
String destinationDiretory = #"c:\zip_files";
String zipFileName = "container.zip";
Boolean unZipWithDirectoryStructure = true;
FSM FSManager = new FSM();
/* Unzips files with or without their directory structure */
FSManager.Unzip(zipFileName,
destinationDirectory,
unZipWithDirectoryStructure);
}
}
Hope it helps.
I use the dll fileselectionmanager to compress and decompress files and folders, it has worked properly in my project. You can see example in your web http://www.fileselectionmanager.com/#Zipping and Unzipping files
and documentation http://www.fileselectionmanager.com/file_selection_manager_documentation