public static void WriteToFile(this Byte[] fileBytes, String filePath) { CreateFolderWhileNotExists(filePath); using (Mutex mutex = new Mutex(false, filePath.GetMutexName())) { mutex.WaitOne(); try { FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); fs.Write(fileBytes, 0, fileBytes.Length); fs.Close(); fs.Dispose(); } catch (Exception ex) { throw ex; } finally { mutex.ReleaseMutex(); } } }
public static void WriteToFile(this Byte[] fileBytes, String filePath, Boolean overwriteIfExist = false, bool throwExceptionIfExist = true) { if (System.IO.File.Exists(filePath) && !overwriteIfExist) { if (throwExceptionIfExist) throw new Exception(String.Format("File '{0}' already exists.", filePath)); return; } CreateFolderWhileNotExists(filePath); using (Mutex mutex = new Mutex(false, filePath.GetMutexName())) { mutex.WaitOne(); try { FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write); fs.Write(fileBytes, 0, fileBytes.Length); fs.Close(); fs.Dispose(); } catch (Exception ex) { throw ex; } finally { mutex.ReleaseMutex(); } } }
public static void WriteToFile(this String content, String filePath, Boolean overwriteIfExist = false) { if (System.IO.File.Exists(filePath) && !overwriteIfExist) throw new Exception(String.Format("File '{0}' already exists.", filePath)); CreateFolderWhileNotExists(filePath); using (Mutex mutex = new Mutex(false, filePath.GetMutexName())) { mutex.WaitOne(); try { using (FileStream fs = new FileStream(filePath, FileMode.Create)) { using (TextWriter tw = new StreamWriter(fs)) { tw.Write(content); tw.Close(); } } } catch (Exception ex) { throw ex; } finally { mutex.ReleaseMutex(); } } }