Here are the examples of the csharp api System.IO.MemoryStream.WriteTo(System.IO.Stream) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
180 Examples
19
Source : HttpServer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private void ServeResourceImage(HttpListenerResponse response, string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
Image image = Image.FromStream(stream);
response.ContentType = "image/png";
try {
Stream output = response.OutputStream;
using (MemoryStream ms = new MemoryStream()) {
image.Save(ms, ImageFormat.Png);
ms.WriteTo(output);
}
output.Close();
} catch (HttpListenerException) {
}
image.Dispose();
response.Close();
return;
}
}
}
response.StatusCode = 404;
response.Close();
}
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteLinedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sidedef, int> sidedefids, IDictionary<Vertex, int> vertexids)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
ushort sid;
int insertpos;
int flags;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all lines
foreach(Linedef l in map.Linedefs)
{
// Convert flags
flags = 0;
foreach(KeyValuePair<string, bool> f in l.Flags)
{
int fnum;
if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
}
// Write properties to stream
writer.Write((UInt16)vertexids[l.Start]);
writer.Write((UInt16)vertexids[l.End]);
writer.Write((UInt16)flags);
writer.Write((UInt16)l.Action);
writer.Write((UInt16)l.Tag);
// Front sidedef
if(l.Front == null) sid = ushort.MaxValue;
else sid = (UInt16)sidedefids[l.Front];
writer.Write(sid);
// Back sidedef
if(l.Back == null) sid = ushort.MaxValue;
else sid = (UInt16)sidedefids[l.Back];
writer.Write(sid);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "LINEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("LINEDEFS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
mem.Flush();
}
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteSidedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sector, int> sectorids)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all sidedefs
foreach(Sidedef sd in map.Sidedefs)
{
// Write properties to stream
writer.Write((Int16)sd.OffsetX);
writer.Write((Int16)sd.OffsetY);
writer.Write(Lump.MakeFixedName(sd.HighTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(sd.LowTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(sd.MiddleTexture, WAD.ENCODING));
writer.Write((UInt16)sectorids[sd.Sector]);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "SIDEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("SIDEDEFS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
mem.Flush();
}
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteSectors(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all sectors
foreach(Sector s in map.Sectors)
{
// Write properties to stream
writer.Write((Int16)s.FloorHeight);
writer.Write((Int16)s.CeilHeight);
writer.Write(Lump.MakeFixedName(s.FloorTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(s.CeilTexture, WAD.ENCODING));
writer.Write((Int16)s.Brightness);
writer.Write((UInt16)s.Effect);
writer.Write((UInt16)s.Tag);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "SECTORS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("SECTORS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
mem.Flush();
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteThings(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
int flags;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all things
foreach(Thing t in map.Things)
{
// Convert flags
flags = 0;
foreach(KeyValuePair<string, bool> f in t.Flags)
{
int fnum;
if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
}
// Write properties to stream
// Write properties to stream
writer.Write((UInt16)t.Tag);
writer.Write((Int16)t.Position.x);
writer.Write((Int16)t.Position.y);
writer.Write((Int16)t.Position.z);
writer.Write((Int16)t.AngleDoom);
writer.Write((UInt16)t.Type);
writer.Write((UInt16)flags);
writer.Write((Byte)t.Action);
writer.Write((Byte)t.Args[0]);
writer.Write((Byte)t.Args[1]);
writer.Write((Byte)t.Args[2]);
writer.Write((Byte)t.Args[3]);
writer.Write((Byte)t.Args[4]);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "THINGS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("THINGS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteVertices(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all vertices
foreach(Vertex v in map.Vertices)
{
// Write properties to stream
writer.Write((Int16)(int)Math.Round(v.Position.x));
writer.Write((Int16)(int)Math.Round(v.Position.y));
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "VERTEXES", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("VERTEXES", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteLinedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sidedef, int> sidedefids, IDictionary<Vertex, int> vertexids)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
ushort sid;
int insertpos;
int flags;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all lines
foreach(Linedef l in map.Linedefs)
{
// Convert flags
flags = 0;
foreach(KeyValuePair<string, bool> f in l.Flags)
{
int fnum;
if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
}
// Add activates to flags
flags |= (l.Activate & manager.Config.LinedefActivationsFilter);
// Write properties to stream
writer.Write((UInt16)vertexids[l.Start]);
writer.Write((UInt16)vertexids[l.End]);
writer.Write((UInt16)flags);
writer.Write((Byte)l.Action);
writer.Write((Byte)l.Args[0]);
writer.Write((Byte)l.Args[1]);
writer.Write((Byte)l.Args[2]);
writer.Write((Byte)l.Args[3]);
writer.Write((Byte)l.Args[4]);
// Front sidedef
if(l.Front == null) sid = ushort.MaxValue;
else sid = (UInt16)sidedefids[l.Front];
writer.Write(sid);
// Back sidedef
if(l.Back == null) sid = ushort.MaxValue;
else sid = (UInt16)sidedefids[l.Back];
writer.Write(sid);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "LINEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("LINEDEFS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteSidedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sector, int> sectorids)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all sidedefs
foreach(Sidedef sd in map.Sidedefs)
{
// Write properties to stream
writer.Write((Int16)sd.OffsetX);
writer.Write((Int16)sd.OffsetY);
writer.Write(Lump.MakeFixedName(sd.HighTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(sd.LowTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(sd.MiddleTexture, WAD.ENCODING));
writer.Write((UInt16)sectorids[sd.Sector]);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "SIDEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("SIDEDEFS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteSectors(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all sectors
foreach(Sector s in map.Sectors)
{
// Write properties to stream
writer.Write((Int16)s.FloorHeight);
writer.Write((Int16)s.CeilHeight);
writer.Write(Lump.MakeFixedName(s.FloorTexture, WAD.ENCODING));
writer.Write(Lump.MakeFixedName(s.CeilTexture, WAD.ENCODING));
writer.Write((Int16)s.Brightness);
writer.Write((UInt16)s.Effect);
writer.Write((UInt16)s.Tag);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "SECTORS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("SECTORS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
}
19
Source : UniversalMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public override void Write(MapSet map, string mapname, int position)
{
UniversalStreamWriter udmfwriter = new UniversalStreamWriter();
// Write map to memory stream
MemoryStream memstream = new MemoryStream();
memstream.Seek(0, SeekOrigin.Begin);
udmfwriter.RememberCustomTypes = true;
udmfwriter.Write(map, memstream, manager.Config.EngineName);
// Find insert position and remove old lump
int insertpos = MapManager.RemoveSpecificLump(wad, "TEXTMAP", position, MapManager.TEMP_MAP_HEADER, manager.Config.MapLumpNames);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
Lump lump = wad.Insert("TEXTMAP", insertpos, (int)memstream.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
memstream.WriteTo(lump.Stream);
// Done
memstream.Dispose();
}
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteThings(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
int flags;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all things
foreach(Thing t in map.Things)
{
// Convert flags
flags = 0;
foreach(KeyValuePair<string, bool> f in t.Flags)
{
int fnum;
if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
}
// Write properties to stream
writer.Write((Int16)t.Position.x);
writer.Write((Int16)t.Position.y);
writer.Write((Int16)t.AngleDoom);
writer.Write((UInt16)t.Type);
writer.Write((UInt16)flags);
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "THINGS", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("THINGS", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
mem.Flush();
}
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void WriteVertices(MapSet map, int position, IDictionary maplumps)
{
MemoryStream mem;
BinaryWriter writer;
Lump lump;
int insertpos;
// Create memory to write to
mem = new MemoryStream();
writer = new BinaryWriter(mem, WAD.ENCODING);
// Go for all vertices
foreach(Vertex v in map.Vertices)
{
// Write properties to stream
writer.Write((Int16)(int)Math.Round(v.Position.x));
writer.Write((Int16)(int)Math.Round(v.Position.y));
}
// Find insert position and remove old lump
insertpos = MapManager.RemoveSpecificLump(wad, "VERTEXES", position, MapManager.TEMP_MAP_HEADER, maplumps);
if(insertpos == -1) insertpos = position + 1;
if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
// Create the lump from memory
lump = wad.Insert("VERTEXES", insertpos, (int)mem.Length);
lump.Stream.Seek(0, SeekOrigin.Begin);
mem.WriteTo(lump.Stream);
mem.Flush();
}
19
Source : MjpegWriter.cs
with MIT License
from AristotelisChantzaras
with MIT License
from AristotelisChantzaras
public void Write(MemoryStream imageStream)
{
StringBuilder sb = new StringBuilder();
//write part header
sb.AppendLine();
sb.AppendLine(this.Boundary);
sb.AppendLine("Content-Type: image/jpeg");
sb.AppendLine("Content-Length: " + imageStream.Length.ToString());
sb.AppendLine();
Write(sb.ToString());
imageStream.WriteTo(this.Stream); //write image data
Write("\r\n");
this.Stream.Flush();
}
19
Source : MjpegWriter.cs
with MIT License
from AristotelisChantzaras
with MIT License
from AristotelisChantzaras
public void Write(MemoryStream imageStream)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine(this.Boundary);
sb.AppendLine("Content-Type: image/jpeg");
sb.AppendLine("Content-Length: " + imageStream.Length.ToString());
sb.AppendLine();
Write(sb.ToString());
imageStream.WriteTo(this.Stream);
Write("\r\n");
this.Stream.Flush();
}
19
Source : PdfFileEditorFeatures.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:PdfFileEditorFeatures
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();
// Create instance of PdfFileEditor clreplaced
PdfFileEditor pdfEditor = new PdfFileEditor();
// Append pages from input file to the port file and save in output file
int start = 1;
int end = 3;
pdfEditor.Append(dataDir + "inFile.pdf", dataDir + "portFile.pdf", start, end, dataDir + "outFile.pdf");
// Concatenate two files and save in the third one
pdfEditor.Concatenate(dataDir + "inFile1.pdf", dataDir + "inFile2.pdf", dataDir + "outFile.pdf");
// Delete specified number of pages from the file
int[] pages = new int[] { 1, 2, 4, 10 };
pdfEditor.Delete(dataDir + "inFile.pdf", pages, dataDir + "outFile.pdf");
// Extract any pages from the file
start = 0;
end = 3;
pdfEditor.OwnerPreplacedword = "ownerpreplaced";
pdfEditor.Extract(dataDir + "inFile.pdf", start, end, dataDir + "outFile.pdf");
// Insert pages from another file into the output file at a specified position
start = 2;
end = 5;
pdfEditor.Insert(dataDir + "inFile.pdf", 4, dataDir + "portFile.pdf", start, end, dataDir + "outFile.pdf");
// Make booklet
pdfEditor.MakeBooklet(dataDir + "inFile.Pdf", dataDir + "outFile.Pdf");
// Make N-Ups
pdfEditor.MakeNUp(dataDir + "inFile.pdf", dataDir + "nupOutFile.pdf", 3, 2);
// Split the front part of the file
pdfEditor.SplitFromFirst(dataDir + "inFile.pdf", 3, dataDir + "outFile.pdf");
// Split the rear part of the file
pdfEditor.SplitToEnd(dataDir + "inFile.pdf", 3, dataDir + "outFile.pdf");
// Split to individual pages
int fileNum = 1;
MemoryStream[] outBuffer = pdfEditor.SplitToPages(dataDir + "inFile.pdf");
foreach (MemoryStream aStream in outBuffer)
{
FileStream outStream = new FileStream("oneByone" + fileNum.ToString() + ".pdf",
FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNum++;
}
// Split to several multi-page pdf doreplacedents
fileNum = 1;
int[][] numberofpage = new int[][] { new int[] { 1, 4 }};
MemoryStream[] outBuffer2 = pdfEditor.SplitToBulks(dataDir + "inFile.pdf", numberofpage);
foreach (MemoryStream aStream in outBuffer2)
{
FileStream outStream = new FileStream("oneByone" + fileNum.ToString() + ".pdf",
FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNum++;
}
// ExEnd:PdfFileEditorFeatures
}
19
Source : ExtractImagesPage.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:ExtractImagesPage
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();
// Open input PDF
PdfExtractor pdfExtractor = new PdfExtractor();
pdfExtractor.BindPdf(dataDir+ "ExtractImages-Page.pdf");
// Set StartPage and EndPage properties to the page number to
// You want to extract images from
pdfExtractor.StartPage = 2;
pdfExtractor.EndPage = 2;
// Extract images
pdfExtractor.ExtractImage();
// Get extracted images
while (pdfExtractor.HasNextImage())
{
// Read image into memory stream
MemoryStream memoryStream = new MemoryStream();
pdfExtractor.GetNextImage(memoryStream);
// Write to disk, if you like, or use it otherwise.
FileStream fileStream = new
FileStream(dataDir+ DateTime.Now.Ticks.ToString() + "_out.jpg", FileMode.Create);
memoryStream.WriteTo(fileStream);
fileStream.Close();
}
// ExEnd:ExtractImagesPage
}
19
Source : SplitPagesToBulkUsingPaths.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:SplitPagesToBulkUsingPaths
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages();
// Create PdfFileEditor object
PdfFileEditor pdfEditor = new PdfFileEditor();
int fileNumber = 1;
// Create array of pages to split
int[][] numberOfPages = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
// Split to bulk
MemoryStream[] outBuffer = pdfEditor.SplitToBulks(dataDir + "MultiplePages.pdf", numberOfPages);
// Save individual files
foreach (MemoryStream aStream in outBuffer)
{
FileStream outStream = new FileStream(dataDir + "File_" + fileNumber.ToString() + "_out.pdf", FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNumber++;
}
// ExEnd:SplitPagesToBulkUsingPaths
}
19
Source : SplitPagesToBulkUsingStreams.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:SplitPagesToBulkUsingStreams
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages();
// Create PdfFileEditor object
PdfFileEditor pdfEditor = new PdfFileEditor();
// Create input stream
FileStream inputStream = new FileStream(dataDir + "MultiplePages.pdf", FileMode.Open);
int fileNumber = 1;
// Create array of pages to split
int[][] numberOfPages = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4} };
// Split to bulk
MemoryStream[] outBuffer = pdfEditor.SplitToBulks(inputStream, numberOfPages);
// Save individual files
foreach (MemoryStream aStream in outBuffer)
{
FileStream outStream = new FileStream(dataDir + "File_" + fileNumber.ToString() + "_out.pdf", FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNumber++;
}
// ExEnd:SplitPagesToBulkUsingStreams
}
19
Source : SplitToIndividualPagesUsingPaths.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:SplitToIndividualPagesUsingPaths
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages();
// Create PdfFileEditor object
PdfFileEditor pdfEditor = new PdfFileEditor();
int fileNumber = 1;
// Split to pages
MemoryStream[] outBuffer = pdfEditor.SplitToPages(dataDir + "input.pdf");
// Save individual files
foreach (MemoryStream aStream in outBuffer)
{
FileStream outStream = new FileStream(dataDir + "File_" + fileNumber.ToString() + "_out.pdf", FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNumber++;
}
// ExEnd:SplitToIndividualPagesUsingPaths
}
19
Source : SplitToIndividualPagesUsingStreams.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:SplitToIndividualPagesUsingStreams
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Pages();
// Create PdfFileEdito object
PdfFileEditor pdfEditor = new PdfFileEditor();
// Create input stream
FileStream inputStream = new FileStream(dataDir + "input.pdf", FileMode.Open);
int fileNumber = 1;
// Split to pages
MemoryStream[] outBuffer = pdfEditor.SplitToPages(inputStream);
// Save individual files
foreach (MemoryStream aStream in outBuffer)
{
FileStream outStream = new FileStream(dataDir + "File_" + fileNumber.ToString() + "_out.pdf", FileMode.Create);
aStream.WriteTo(outStream);
outStream.Close();
fileNumber++;
}
// ExEnd:SplitToIndividualPagesUsingStreams
}
19
Source : ExtractImagesStream.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:ExtractImagesStream
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Images();
// Open input PDF
PdfExtractor pdfExtractor = new PdfExtractor();
pdfExtractor.BindPdf(dataDir+ "ExtractImages-Stream.pdf");
// Extract images
pdfExtractor.ExtractImage();
// Get all the extracted images
while (pdfExtractor.HasNextImage())
{
// Read image into memory stream
MemoryStream memoryStream = new MemoryStream();
pdfExtractor.GetNextImage(memoryStream);
// Write to disk, if you like, or use it otherwise.
FileStream fileStream = new
FileStream(dataDir+ DateTime.Now.Ticks.ToString() + "_out.jpg", FileMode.Create);
memoryStream.WriteTo(fileStream);
fileStream.Close();
}
// ExEnd:ExtractImagesStream
}
19
Source : GraphicsFactory.cs
with GNU General Public License v3.0
from AtomCrafty
with GNU General Public License v3.0
from AtomCrafty
public override long ToBinary(YukaGraphics graphics, Stream s) {
long offset = s.Position;
BinaryWriter bw = new BinaryWriter(s, Encoding.ASCII, true);
bw.Write(YKG_HEADER);
Bitmap colorLayer = graphics.bitmap;
MemoryStream colorStream = new MemoryStream();
colorLayer.Save(colorStream, ImageFormat.Png);
// header length
int curoffset = 0x40;
bw.Write(curoffset);
bw.Write((int)colorStream.Length);
curoffset += (int)colorStream.Length;
// no opacity mask
bw.Write((long)0);
if(graphics.metaData != null) {
bw.Write(curoffset);
bw.Write(graphics.metaData.Length);
}
else {
bw.Write((long)0);
}
colorStream.WriteTo(s);
colorStream.Close();
/*
if(alphaLayer != null) {
alphaStream.WriteTo(s);
}
alphaStream.Close();
*/
if(graphics.metaData != null) {
bw.Write(graphics.metaData);
}
bw.Close();
return s.Position - offset;
}
19
Source : RawFactory.cs
with GNU General Public License v3.0
from AtomCrafty
with GNU General Public License v3.0
from AtomCrafty
public override long ToBinary(YukaRaw data, Stream s) {
using(MemoryStream ms = new MemoryStream(data.data)) {
ms.WriteTo(s);
return ms.Position;
}
}
19
Source : Program.cs
with MIT License
from BeginTry
with MIT License
from BeginTry
private static void CreateExcelSpreadsheet()
{
using (MemoryStream ms = Utils.ExportDataSetToExcel(AllDatatablesForExcel))
{
using (FileStream fs = new FileStream(ExcelSpreadsheet.FullName, FileMode.Create))
{
ms.WriteTo(fs);
}
}
}
19
Source : ElementStore.cs
with MIT License
from bonsai-rx
with MIT License
from bonsai-rx
public static void SaveElement(XmlSerializer serializer, string fileName, object element)
{
using (var memoryStream = new MemoryStream())
using (var writer = XmlnsIndentedWriter.Create(memoryStream, DefaultWriterSettings))
{
serializer.Serialize(writer, element);
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
memoryStream.WriteTo(fileStream);
}
}
}
19
Source : SilverlightSerializer.cs
with MIT License
from CalciumFramework
with MIT License
from CalciumFramework
private static void WriteProperties(Type itemType, object item, BinaryWriter writer)
{
var propertyStream = new MemoryStream();
var pw = new BinaryWriter(propertyStream);
byte propCount = 0;
//Get the properties of the object
var properties = GetPropertyInfo(itemType);
foreach (var property in properties)
{
if (IsChecksum && IsLoud)
{
Debug.WriteLine(" ----> {0} on {1}", property.Name, item.ToString());
}
object value;
try
{
value = property.GetValue(item, null);
}
catch (Exception ex)
{
throw new Exception("Unable to retrieve property value. Property name: " + property.Name, ex);
}
//Don't store null values
if (value == null)
continue;
//Don't store empty collections
if ((value as ICollection)?.Count == 0)
continue;
//Don't store empty arrays
var arrayValue = value as Array;
if (arrayValue?.Length == 0)
continue;
//Check whether the value differs from the default
lock (Vanilla)
{
if (value.Equals(property.GetValue(Vanilla[itemType], null)))
continue;
}
//If we get here then we need to store the property
propCount++;
pw.Write(GetPropertyDefinitionId(property.Name));
SerializeObject(value, pw, property.PropertyType);
}
writer.Write(propCount);
if (Verbose)
writer.Write((int)propertyStream.Length);
propertyStream.WriteTo(writer.BaseStream);
}
19
Source : SilverlightSerializer.cs
with MIT License
from CalciumFramework
with MIT License
from CalciumFramework
private static void WriteFields(Type itemType, object item, BinaryWriter writer)
{
var fieldStream = new MemoryStream();
var fw = new BinaryWriter(fieldStream);
byte fieldCount = 0;
//Get the public fields of the object
var fields = GetFieldInfo(itemType);
foreach (var field in fields)
{
var value = field.GetValue(item);
//Don't store null values
if (value == null)
continue;
//Don't store empty collections
if (value is ICollection)
if ((value as ICollection).Count == 0)
continue;
//Don't store empty arrays
if (value is Array)
if ((value as Array).Length == 0)
continue;
//Check whether the value differs from the default
lock (Vanilla)
{
if (value.Equals(field.GetValue(Vanilla[itemType])))
continue;
}
//if we get here then we need to store the field
fieldCount++;
fw.Write(GetPropertyDefinitionId(field.Name));
SerializeObject(value, fw, field.FieldType);
}
writer.Write(fieldCount);
if (Verbose)
writer.Write((int)fieldStream.Length);
fieldStream.WriteTo(writer.BaseStream);
}
19
Source : SilverlightSerializer.cs
with MIT License
from CalciumFramework
with MIT License
from CalciumFramework
public static void Serialize(object item, Stream outputStream)
{
CreateStacks();
try
{
_ktStack.Push(_knownTypes);
_piStack.Push(_propertyIds);
_soStack.Push(_seenObjects);
_propertyIds = new List<string>();
_knownTypes = new List<Type>();
_seenObjects = new Dictionary<object, int>();
var strm = new MemoryStream();
var wr = new BinaryWriter(strm);
SerializeObject(item, wr);
var outputWr = new BinaryWriter(outputStream);
outputWr.Write("SerV3");
outputWr.Write(_knownTypes.Count);
//New, store the verbose property
outputWr.Write(Verbose);
foreach (var kt in _knownTypes)
{
outputWr.Write(kt.replacedemblyQualifiedName);
}
outputWr.Write(_propertyIds.Count);
foreach (var pi in _propertyIds)
{
outputWr.Write(pi);
}
strm.WriteTo(outputStream);
}
finally
{
_knownTypes = _ktStack.Pop();
_propertyIds = _piStack.Pop();
_seenObjects = _soStack.Pop();
}
}
19
Source : ResponseExtensions.cs
with MIT License
from ClosedXML
with MIT License
from ClosedXML
public static void DeliverWorkbook(this HttpResponse httpResponse, XLWorkbook workbook, string fileName, string contentType = "application/vnd.openxmlformats-officedoreplacedent.spreadsheetml.sheet")
{
httpResponse.Clear();
httpResponse.ContentType = contentType;
httpResponse.AddHeader("content-disposition", $"attachment;filename=\"{fileName}\"");
// Flush the workbook to the Response.OutputStream
using (var memoryStream = new MemoryStream())
{
workbook.SaveAs(memoryStream);
memoryStream.WriteTo(httpResponse.BodyStream());
memoryStream.Close();
}
httpResponse.End();
}
19
Source : ResponseExtensions.cs
with MIT License
from ClosedXML
with MIT License
from ClosedXML
public static void DeliverToHttpResponse(this XLWorkbook workbook, HttpResponse httpResponse, string fileName, string contentType = "application/vnd.openxmlformats-officedoreplacedent.spreadsheetml.sheet")
{
httpResponse.Clear();
httpResponse.ContentType = contentType;
httpResponse.AddHeader("content-disposition", $"attachment;filename=\"{fileName}\"");
// Flush the workbook to the Response.OutputStream
using (var memoryStream = new MemoryStream())
{
workbook.SaveAs(memoryStream);
memoryStream.WriteTo(httpResponse.BodyStream());
memoryStream.Close();
}
httpResponse.End();
}
19
Source : DemoController.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public ActionResult UploadFile(string fileBase64, string fileName)
{
byte[] bytes = fileBase64.ToBytes_FromBase64Str();
string fileDir = Path.Combine(GlobalSwitch.WebRootPath, "Upload", "File");
if (!Directory.Exists(fileDir))
Directory.CreateDirectory(fileDir);
string filePath = Path.Combine(fileDir, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
using (MemoryStream m = new MemoryStream(bytes))
{
m.WriteTo(fileStream);
}
}
return Success();
}
19
Source : DemoController.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public ActionResult UploadFile(string fileBase64, string fileName,string data)
{
byte[] bytes = fileBase64.ToBytes_FromBase64Str();
string fileDir = System.Web.HttpContext.Current.Server.MapPath("~/Upload/File");
if (!Directory.Exists(fileDir))
Directory.CreateDirectory(fileDir);
string filePath = Path.Combine(fileDir, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
using (MemoryStream m = new MemoryStream(bytes))
{
m.WriteTo(fileStream);
}
}
return Success();
}
19
Source : CommonController.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
public ActionResult UploadFile(string fileName, string data, string fileType)
{
string fileBase64 = GetBase64String(data).Replace(" ", "+");
byte[] bytes = fileBase64.ToBytes_FromBase64Str();
string relativeDir = $"/Upload/File/{Guid.NewGuid().ToString()}";
string absoluteDir = PathHelper.GetAbsolutePath($"~{relativeDir}");
if (!Directory.Exists(absoluteDir))
Directory.CreateDirectory(absoluteDir);
string filePath = Path.Combine(absoluteDir, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
using (MemoryStream m = new MemoryStream(bytes))
{
m.WriteTo(fileStream);
}
}
string url = $"{GlobalSwitch.WebRootUrl}{relativeDir}/{fileName}";
var res = new
{
success = true,
src = url
};
return JsonContent(res.ToJson());
string GetBase64String(string base64Url)
{
string parttern = "^.*?base64,(.*?)$";
var match = Regex.Match(base64Url, parttern);
return match.Groups[1].ToString();
}
}
19
Source : CommonController.cs
with MIT License
from Coldairarrow
with MIT License
from Coldairarrow
public ActionResult UploadFile(string fileName, string data, string fileType)
{
string fileBase64 = GetBase64String(data);
byte[] bytes = fileBase64.ToBytes_FromBase64Str();
string relativeDir = $"/Upload/File/{Guid.NewGuid().ToString()}";
string absoluteDir = PathHelper.GetAbsolutePath($"~{relativeDir}");
if (!Directory.Exists(absoluteDir))
Directory.CreateDirectory(absoluteDir);
string filePath = Path.Combine(absoluteDir, fileName);
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
using (MemoryStream m = new MemoryStream(bytes))
{
m.WriteTo(fileStream);
}
}
string url = $"{GlobalSwitch.WebRootUrl}{relativeDir}/{fileName}";
var res = new
{
success = true,
src = url
};
return JsonContent(res.ToJson());
string GetBase64String(string base64Url)
{
string parttern = "^.*?base64,(.*?)$";
var match = Regex.Match(base64Url, parttern);
return match.Groups[1].ToString();
}
}
19
Source : LuaMgr.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
public void WriteFileFromBytes(string path, byte[] bytes)
{
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
if (File.Exists(path))
{
File.Delete(path);
}
using (MemoryStream ms = new MemoryStream(bytes))
{
using (FileStream fs = new FileStream(path, FileMode.Create))
{
ms.WriteTo(fs);
}
}
}
19
Source : System_IO_MemoryStream_Binding.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
static StackObject* WriteTo_22(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.Stream @stream = (System.IO.Stream)typeof(System.IO.Stream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.IO.MemoryStream instance_of_this_method = (System.IO.MemoryStream)typeof(System.IO.MemoryStream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
instance_of_this_method.WriteTo(@stream);
return __ret;
}
19
Source : Xlsx.cs
with MIT License
from CSOIreland
with MIT License
from CSOIreland
internal void SaveToFile(string fileNamePath, MemoryStream doreplacedentStream)
{
doreplacedentStream.Seek(0, SeekOrigin.Begin);
FileStream fs = new FileStream(fileNamePath, FileMode.CreateNew);
doreplacedentStream.WriteTo(fs);
fs.Close();
}
19
Source : SauceInfoDialog.cs
with MIT License
from cwensley
with MIT License
from cwensley
void RemoveSauce()
{
sauce = null;
if (!directSave)
return;
if (doreplacedent != null)
{
doreplacedent.Sauce = null;
doreplacedent.IsModified = true;
}
else
{
bool hreplacedauce;
using (var ms = new MemoryStream())
{
using (var stream = file.Open(FileMode.Open))
{
var ss = new SauceStream(stream);
hreplacedauce = ss.Sauce != null;
if (hreplacedauce)
ss.WriteTo(ms);
}
if (hreplacedauce)
{
file.Delete();
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
using (var newfile = file.Open(FileMode.CreateNew))
{
ms.WriteTo(newfile);
}
}
}
}
}
19
Source : SauceInfoDialog.cs
with MIT License
from cwensley
with MIT License
from cwensley
void Save()
{
if (!directSave)
return;
if (doreplacedent != null)
{
doreplacedent.Sauce = sauce;
doreplacedent.IsModified = true;
}
else
{
using (var ms = new MemoryStream())
{
using (var stream = file.Open(FileMode.Open))
{
var ss = new SauceStream(stream);
ss.WriteTo(ms);
sauce.SaveSauce(ms, false);
}
file.Delete();
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
using (var newfile = file.Open(FileMode.CreateNew))
{
ms.WriteTo(newfile);
}
}
}
}
19
Source : XmlExtensions.cs
with MIT License
from cwensley
with MIT License
from cwensley
public static void SaveXml(this IXmlReadable obj, string fileName, string doreplacedentElementName = "object")
{
using (var stream = new MemoryStream())
{
SaveXml(obj, stream, doreplacedentElementName);
stream.Position = 0;
using (var fileStream = File.Create(fileName))
{
stream.WriteTo(fileStream);
}
}
}
19
Source : NamedPipeTransport.cs
with Apache License 2.0
from cyanfish
with Apache License 2.0
from cyanfish
public void Commit()
{
lock (_pipeStream)
{
if (_packetBuffer.Length > 0)
{
_packetBuffer.WriteTo(_pipeStream);
}
foreach (var payload in _trailingPayloads)
{
_pipeStream.Write(payload, 0, payload.Length);
}
}
}
19
Source : FileUpload.razor.cs
with MIT License
from DataJuggler
with MIT License
from DataJuggler
private async void OnFileChange(InputFileChangeEventArgs eventArgs)
{
//// Get access to the file
IBrowserFile file = eventArgs.File;
// locals
UploadedFileInfo uploadedFileInfo = null;
bool abort = false;
// locals
MemoryStream ms = null;
// verify the file exists
if (file != null)
{
try
{
// the partialGuid is need to ensure uniqueness
string partialGuid = Guid.NewGuid().ToString().Substring(0, PartialGuidLength);
// create the uploadedFileInfo
uploadedFileInfo = new UploadedFileInfo(file, partialGuid, AppendPartialGuid, UploadFolder);
// if the file is too large
if ((MaxFileSize > 0) && (file.Size > MaxFileSize))
{
// Show the FileTooLargeMessage
status = FileTooLargeMessage;
// Upload was aborted
uploadedFileInfo.Aborted = true;
uploadedFileInfo.ErrorMessage = FileTooLargeMessage;
uploadedFileInfo.Exception = new Exception("The file uploaded was too large.");
}
else
{
// Create a new instance of a 'FileInfo' object.
FileInfo fileInfo = new FileInfo(file.Name);
// Set the extension. The ToLower is for just in case. I don't know if it's even possible for an extension to be upper case
uploadedFileInfo.Extension = fileInfo.Extension.ToLower();
// if FilterByExtension is true and the AllowedExtensions text exists
if ((FilterByExtension) && (!String.IsNullOrWhiteSpace(AllowedExtensions)))
{
// verify the extension exists
if (!String.IsNullOrWhiteSpace(fileInfo.Extension))
{
// If the allowed extensions // fixed issue where uploading
abort = !AllowedExtensions.ToLower().Contains(fileInfo.Extension.ToLower());
}
else
{
// you must have an extension
abort = true;
}
}
// Set aborted to true
uploadedFileInfo.Aborted = abort;
// if we should continue
if (!abort)
{
//// create the memoryStream
ms = new MemoryStream();
using var stream = file.OpenReadStream(MaxFileSize);
byte[] buffer = new byte[4 * 1096];
int bytesRead;
double totalRead = 0;
progressVisible = true;
while ((bytesRead = await stream.ReadAsync(buffer)) != 0)
{
totalRead += bytesRead;
await ms.WriteAsync(buffer);
progressPercent = (int)((totalRead / file.Size) * 100);
StateHasChanged();
}
// finished uploading
progressVisible = false;
//// await for the data to be copied to the memory stream
//await file.OpenReadStream(MaxFileSize).CopyToAsync(ms);
// Check for abort 1 more time
uploadedFileInfo = CheckSize(fileInfo.Extension, ms, uploadedFileInfo);
// if abort
if (uploadedFileInfo.Aborted)
{
// Do not process due to size is not valid, message has already been set
abort = true;
}
}
// if we should continue
if (!abort)
{
// if the value for SaveToDisk is true
if (SaveToDisk)
{
// set the full path
string path = Path.Combine(UploadFolder, uploadedFileInfo.FullName);
// save the file using the FullName (If AppendPartialGuid is still true, than the Name.PartialGuid is the FullName
using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
{
// write out the file
ms.WriteTo(fileStream);
}
}
else
{
// Set the MemoryStream, to allow people to save outside of the project
// folder, to disk or other processing like virus scans.
uploadedFileInfo.Stream = ms;
}
// if there is a CustomSave
if (!String.IsNullOrWhiteSpace(CustomSuccessMessage))
{
// Show the CustomSuccessMessage
status = CustomSuccessMessage;
}
else
{
// set the status
status = $"Saved file {file.Size} bytes from {file.Name}";
}
// Set additional properties for UploadFileInfo from this component; these values may be null.
uploadedFileInfo.CustomId = CustomId;
uploadedFileInfo.Tag = Tag;
// The upload has completed
UploadComplete = true;
}
else
{
// If a CustomExtensionMessage has been set
if (!string.IsNullOrWhiteSpace(CustomExtensionMessage))
{
// Display the Custom extension doesn't validate message
uploadedFileInfo.ErrorMessage = CustomExtensionMessage;
}
else
{
// Can't think of a better message than this yet, just woke up
uploadedFileInfo.ErrorMessage = "The file uploaded is an invalid extension.";
}
// Show the exception
uploadedFileInfo.Exception = new Exception(uploadedFileInfo.ErrorMessage);
}
}
}
catch (Exception error)
{
// Upload was aborted
uploadedFileInfo.Aborted = true;
// Store the Exception
uploadedFileInfo.Exception = error;
// if a CustomErrorMessage is set
if (!String.IsNullOrWhiteSpace(CustomErrorMessage))
{
// Show the custom error message
status = CustomErrorMessage;
}
else
{
// show the full error
status = error.ToString();
}
// set the error message
uploadedFileInfo.ErrorMessage = status;
}
finally
{
// Notify the caller the upload was successful or aborted due to an error
FileUploaded(uploadedFileInfo);
}
}
}
19
Source : Streams.cs
with MIT License
from dcomms
with MIT License
from dcomms
public static void WriteBufTo(MemoryStream buf, Stream output)
{
buf.WriteTo(output);
}
19
Source : Streams.cs
with MIT License
from dcomms
with MIT License
from dcomms
public static int WriteBufTo(MemoryStream buf, byte[] output, int offset)
{
#if PORTABLE
byte[] bytes = buf.ToArray();
bytes.CopyTo(output, offset);
return bytes.Length;
#else
int size = (int)buf.Length;
buf.WriteTo(new MemoryStream(output, offset, size, true));
return size;
#endif
}
19
Source : BinaryImageViewer.aspx.cs
with Apache License 2.0
from DevExpress
with Apache License 2.0
from DevExpress
protected void Page_Load(object sender, EventArgs e) {
// Here an image should be obtained from a database
// We read it from a file for demostration purposes
byte[] image = File.ReadAllBytes(Server.MapPath("~/App_Data/UploadedData/avatar.jpg"));
// Now 'image' contains harmfull html: "<body onload=\'alert(1)\'></body>"
Response.ClearHeaders();
//Response.ContentType = "image"; // Not secure
Response.ContentType = "image/jpeg"; // Specify content-type to prevent the vulnerability
Response.Headers.Add("X-Content-Type-Options", "nosniff"); // Additional validation
using(MemoryStream ms = new MemoryStream(image))
ms.WriteTo(Response.OutputStream);
Response.End();
}
19
Source : UploadingBinaryImages.cs
with Apache License 2.0
from DevExpress
with Apache License 2.0
from DevExpress
[HttpGet]
public ActionResult BinaryImageViewer() {
// Here an image should be obtained from a database
// We read it from a file for demostration purposes
byte[] image = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/UploadedData/avatar.jpg"));
// Now 'image' contains harmfull html: "<body onload=\'alert(1)\'></body>"
Response.ClearHeaders();
// Response.ContentType = "image"; // It is not secure
Response.ContentType = "image/jpeg"; // Specify content-type to prevent the vulnerability
Response.Headers.Add("X-Content-Type-Options", "nosniff"); // Additional valitation
using(MemoryStream ms = new MemoryStream(image))
ms.WriteTo(Response.OutputStream);
return new FileContentResult(image, Response.ContentType);
}
19
Source : Hook.cs
with The Unlicense
from devunt
with The Unlicense
from devunt
private static IntPtr GereplacedemTooltipDescription(IntPtr self, IntPtr descriptionText, IntPtr additionalText)
{
if ((NativeMethods.GetAsyncKeyState(0x10) & 0x8000) > 0) // VK_SHIFT
{
try
{
var itemId = Marshal.ReadInt32(self, 300);
bool isHq = false, isCollectible = false;
if (itemId > 1000000)
{
itemId -= 1000000;
isHq = true;
}
else if (itemId > 500000)
{
itemId -= 500000;
isCollectible = true;
}
if (CachedBufferAddrs.TryGetValue(itemId, out var cachedBufferAddr))
{
return _gereplacedemTooltipDescriptionOrigMethod(self, descriptionText, cachedBufferAddr);
}
using (var ms = new MemoryStream())
{
if (_data.Shops.TryGetValue(itemId, out var shops))
{
var i = 0;
foreach (var shop in shops)
{
var cosreplacedem = _data.Metadata.Items[shop.CostId];
var lastCode = (cosreplacedem.Name[cosreplacedem.Name.Length - 1] - 0xAC00) % 28;
var josa = lastCode == 0 || lastCode == 8 ? "로" : "으로";
ms.WriteColoredString("> 다음 NPC 에서 ", Color.Normal);
ms.WriteColoredString($"{shop.CostAmount} {cosreplacedem.Name}", Color.Cost);
ms.WriteColoredString($"{josa} 교환", Color.Normal);
ms.WriteByte(0xA);
foreach (var sellerId in shop.SellerIds)
{
var npc = _data.Metadata.NPCs[sellerId];
var name = npc.replacedle == "" || npc.replacedle.StartsWith("상인") ? npc.Name : npc.replacedle;
foreach (var location in npc.Locations)
{
ms.WriteColoredString(" - ", Color.Misc);
ms.WriteColoredString(_data.Metadata.Placenames[location.PlaceId], Color.Place);
ms.WriteColoredString($" - {name} ({location.X}, {location.Y})", Color.Misc);
ms.WriteByte(0xA);
i++;
}
if (i >= 10)
{
i = 0;
ms.WriteColoredString(" - ...이하 생략됨", Color.Misc);
ms.WriteByte(0xA);
break;
}
}
}
}
if (_data.GCShops.TryGetValue(itemId, out var gcshop))
{
ms.WriteColoredString("> 총사령부에서 ", Color.Normal);
ms.WriteColoredString($"{gcshop.CostAmount} 군표", Color.Cost);
ms.WriteColoredString("로 교환", Color.Normal);
ms.WriteByte(0xA);
}
if (_data.FCShops.TryGetValue(itemId, out var fcshop))
{
ms.WriteColoredString("> 총사령부에서 ", Color.Normal);
ms.WriteColoredString($"{fcshop.CostAmount} 부대 명성", Color.Cost);
ms.WriteColoredString("으로 교환", Color.Normal);
ms.WriteByte(0xA);
}
if (_data.Craftings.TryGetValue(itemId, out var craftings))
{
if (craftings.Length == 1)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[craftings[0].ClreplacedJobCat];
ms.WriteColoredString("> ", Color.Normal);
ms.WriteColoredString($"{craftings[0].Level}레벨 {clreplacedjobName}", Color.Cost);
ms.WriteColoredString("로 제작", Color.Normal);
ms.WriteByte(0xA);
}
else
{
ms.WriteColoredString("> 다음 제작자 클래스로 제작", Color.Normal);
ms.WriteByte(0xA);
foreach (var crafting in craftings)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[crafting.ClreplacedJobCat];
ms.WriteColoredString($" - {crafting.Level}레벨 {clreplacedjobName}", Color.Cost);
ms.WriteByte(0xA);
}
}
}
if (_data.Gatherings.TryGetValue(itemId, out var gatherings))
{
if (gatherings.Length == 1)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[gatherings[0].ClreplacedJobCat];
ms.WriteColoredString("> ", Color.Normal);
ms.WriteColoredString($"{gatherings[0].Level}레벨 {clreplacedjobName}", Color.Cost);
ms.WriteColoredString("로 채집", Color.Normal);
ms.WriteByte(0xA);
}
else
{
ms.WriteColoredString("> 다음 채집가 클래스로 채집", Color.Normal);
ms.WriteByte(0xA);
foreach (var gathering in gatherings)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[gathering.ClreplacedJobCat];
ms.WriteColoredString($" - {gathering.Level}레벨 {clreplacedjobName}", Color.Cost);
ms.WriteByte(0xA);
}
}
}
if (_data.RetainerTasks.TryGetValue(itemId, out var retainerTasks))
{
if (retainerTasks.Length == 1)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[retainerTasks[0].ClreplacedJobCat];
clreplacedjobName = clreplacedjobName == "투사 마법사" ? "전투" : clreplacedjobName;
ms.WriteColoredString("> ", Color.Normal);
ms.WriteColoredString($"{clreplacedjobName} 집사 {retainerTasks[0].Level}레벨", Color.Cost);
ms.WriteColoredString("로 조달", Color.Normal);
ms.WriteByte(0xA);
}
else
{
ms.WriteColoredString("> 다음 클래스 집사로 조달", Color.Normal);
ms.WriteByte(0xA);
foreach (var retainerTask in retainerTasks)
{
var clreplacedjobName = _data.Metadata.ClreplacedJobCats[retainerTask.ClreplacedJobCat];
clreplacedjobName = clreplacedjobName == "투사 마법사" ? "전투" : clreplacedjobName;
ms.WriteColoredString($" - {clreplacedjobName} 집사 {retainerTask.Level}레벨", Color.Cost);
ms.WriteByte(0xA);
}
}
}
if (_data.InstanceContentIds.TryGetValue(itemId, out var icIds))
{
ms.WriteColoredString("> 다음 임무에서 입수", Color.Normal);
ms.WriteByte(0xA);
for (var i = 0; i < icIds.Length; i += 2)
{
var icNames = string.Join(", ", icIds.Skip(i).Take(2).Select(icId => _data.Metadata.InstanceContents[icId].Name));
ms.WriteColoredString($" - {icNames}", Color.Place);
ms.WriteByte(0xA);
}
}
#if DEBUG
ms.WriteColoredString($"> ID: {itemId}", Color.Debug);
ms.WriteByte(0xA);
ms.WriteColoredString($"> HQ: {isHq}, Cltb: {isCollectible}", Color.Debug);
ms.WriteByte(0xA);
#endif
if (ms.Length > 0)
{
using (var ms2 = new MemoryStream())
{
if (additionalText != IntPtr.Zero)
{
var bytes = Util.ReadCStringAsBytes(additionalText);
ms2.Write(bytes, 0, bytes.Length);
ms2.WriteByte(0xA);
}
ms2.WriteByte(0xA);
ms2.WriteColoredString("[입수 방법]", Color.Header);
ms2.WriteByte(0xA);
ms.WriteTo(ms2);
var buffer = ms2.ToArray();
var size = Math.Min(buffer.Length, 2047);
var bufferAddr = Marshal.AllocHGlobal(size + 1);
CachedBufferAddrs[itemId] = bufferAddr;
Util.WriteMemory(bufferAddr, buffer, size);
Marshal.WriteByte(bufferAddr, size, 0);
return _gereplacedemTooltipDescriptionOrigMethod(self, descriptionText, bufferAddr);
}
}
}
}
catch (Exception ex)
{
WriteLine(ex);
}
}
return _gereplacedemTooltipDescriptionOrigMethod(self, descriptionText, additionalText);
}
19
Source : File.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public static void WriteStream(String FileName, MemoryStream In)
{
FileStream fs = null;
int times = 0;
while (true)
{
try
{
if (System.IO.File.Exists(FileName))
{
System.IO.File.Delete(FileName);
}
fs = new FileStream(FileName, FileMode.CreateNew);
In.WriteTo(fs);
fs.Close();
return;
}
catch (IOException e)
{
uint hResult = (uint)System.Runtime.InteropServices.Marshal.GetHRForException(e);
if (hResult == ERR_PROCESS_CANNOT_ACCESS_FILE)
{
if (times > 10)
{
//Maybe another program has some trouble with file
//We must exit now
throw e;
}
System.Threading.Thread.Sleep(200);
times++;
}
else
{
throw e;
}
}
}
}
19
Source : NetworkChannelHelper.cs
with BSD 3-Clause "New" or "Revised" License
from edouardlicn
with BSD 3-Clause "New" or "Revised" License
from edouardlicn
public bool Serialize<T>(T packet, Stream destination) where T : Packet
{
PacketBase packetImpl = packet as PacketBase;
if (packetImpl == null)
{
Log.Warning("Packet is invalid.");
return false;
}
if (packetImpl.PacketType != PacketType.ClientToServer)
{
Log.Warning("Send packet invalid.");
return false;
}
m_CachedStream.SetLength(m_CachedStream.Capacity); // 此行防止 Array.Copy 的数据无法写入
m_CachedStream.Position = 0L;
CSPacketHeader packetHeader = ReferencePool.Acquire<CSPacketHeader>();
Serializer.Serialize(m_CachedStream, packetHeader);
ReferencePool.Release(packetHeader);
Serializer.SerializeWithLengthPrefix(m_CachedStream, packet, PrefixStyle.Fixed32);
ReferencePool.Release(packet.GetType(), packet);
m_CachedStream.WriteTo(destination);
return true;
}
19
Source : NetworkChannelHelper.cs
with MIT License
from EllanJiang
with MIT License
from EllanJiang
public bool Serialize<T>(T packet, Stream destination) where T : Packet
{
PacketBase packetImpl = packet as PacketBase;
if (packetImpl == null)
{
Log.Warning("Packet is invalid.");
return false;
}
if (packetImpl.PacketType != PacketType.ClientToServer)
{
Log.Warning("Send packet invalid.");
return false;
}
m_CachedStream.SetLength(m_CachedStream.Capacity); // 此行防止 Array.Copy 的数据无法写入
m_CachedStream.Position = 0L;
CSPacketHeader packetHeader = ReferencePool.Acquire<CSPacketHeader>();
Serializer.Serialize(m_CachedStream, packetHeader);
ReferencePool.Release(packetHeader);
Serializer.SerializeWithLengthPrefix(m_CachedStream, packet, PrefixStyle.Fixed32);
ReferencePool.Release((IReference)packet);
m_CachedStream.WriteTo(destination);
return true;
}
See More Examples