本文整理汇总了C#中System.IO.FileInfo.OpenRead方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.FileInfo.OpenRead方法的具体用法?C# System.IO.FileInfo.OpenRead怎么用?C# System.IO.FileInfo.OpenRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileInfo
的用法示例。
在下文中一共展示了System.IO.FileInfo.OpenRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: QueueForUpload
private static void QueueForUpload(FileInfo file, string folder)
{
var operation = new AsyncOperationModel
{
Description = "Uploading " + file.Name + " to " + folder,
};
var stream = file.OpenRead();
var fileSize = stream.Length;
var fileName = file.Name;
if (folder != "/")
fileName = folder + "/" + file.Name;
ApplicationModel.Current.Client.UploadAsync(
fileName,
new NameValueCollection(),
stream,
(_, bytesUploaded) => operation.ProgressChanged(bytesUploaded, fileSize, GetProgressText(bytesUploaded, fileSize)))
.UpdateOperationWithOutcome(operation)
.ContinueOnUIThread(task => stream.Dispose());
ApplicationModel.Current.AsyncOperations.RegisterOperation(operation);
}
示例2: AddFile
public bool AddFile(string localFilePath, int roomId)
{
var roomsApi = getRoomsApi();
string fileId = null;
int maxFileSize = 10000000; // bytes.. 10 MB
System.IO.FileInfo fi = new System.IO.FileInfo(localFilePath);
if (!fi.Exists)
{
_lastError = "File doesn't exist.";
}
else if (fi.Length > maxFileSize)
{
_lastError = "File size cannot be greater than " + maxFileSize + " bytes.";
}
else
{
string fileName = fi.Name;
byte[] fileContent = new byte[fi.Length];
System.IO.Stream str = fi.OpenRead();
str.Read(fileContent, 0, Convert.ToInt32(fi.Length));
string fileData = Convert.ToBase64String(fileContent);
var result = roomsApi.PostFile(getAuthHeader(), roomId, 0, fileName, fileData);
if (result.success && result.data != null) fileId = result.data.ToString();
else _lastError = result.code.ToString();
str.Close();
str.Dispose();
}
return fileId != null;
}
示例3: ReadAll
public void ReadAll()
{
new FileInfo(@".\Testing\Test.txt").Write("This is a test");
var File = new System.IO.FileInfo(@".\Testing\Test.txt");
using (System.IO.FileStream Test = File.OpenRead())
{
Assert.Equal("This is a test", Test.ReadAll());
}
}
示例4: ReadAllBinary
public void ReadAllBinary()
{
new FileInfo(@".\Testing\Test.txt").Write("This is a test");
var File = new System.IO.FileInfo(@".\Testing\Test.txt");
using (System.IO.FileStream Test = File.OpenRead())
{
byte[] Content = Test.ReadAllBinary();
Assert.Equal("This is a test", System.Text.Encoding.ASCII.GetString(Content, 0, Content.Length));
}
}
示例5: DUHelper
/// <summary>
/// Create a new instance of the du helper from a file location.
/// </summary>
/// <param name="fileName">The full file name of the file to load data from.</param>
public DUHelper(string fileName)
{
System.IO.FileInfo file = new System.IO.FileInfo(fileName);
if (!file.Exists) throw new System.IO.FileNotFoundException("Could not find file.", fileName);
System.IO.FileStream fs = file.OpenRead();
byte[] filedat = new byte[fs.Length];
fs.Read(filedat, 0, filedat.Length);
fs.Close();
LoadFromBytes(filedat);
}
示例6: Get
public System.IO.Stream Get(string fileName)
{
var prefix = fileName.Substring(0, 2);
var file = new System.IO.FileInfo(System.IO.Path.Combine(this.RootPath, prefix, fileName));
if (file.Exists)
{
return file.OpenRead();
}
else
{
throw new Exception("file not found");
}
}
示例7: ProcessRequest
//***************************************************************************
// Public Methods
//
public void ProcessRequest(HttpContext context)
{
HttpRequest req = context.Request;
string
qsImgUrl = req.QueryString["src"],
qsAct = req.QueryString["a"];
bool buttonActive = (string.IsNullOrEmpty(qsAct) || qsAct == "1");
string srcUrl = WebUtil.MapPath(WebUtil.UrlDecode(qsImgUrl));
System.IO.FileInfo fiImg = new System.IO.FileInfo(srcUrl);
if (!fiImg.Exists)
{ context.Response.StatusCode = 404; }
else
{
byte[] imgData = null;
string contentType = string.Format("image/{0}", fiImg.Extension.TrimStart('.'));
using (System.IO.FileStream fs = fiImg.OpenRead())
{
if (buttonActive)
{
// If the button is active, just load the image directly.
imgData = new byte[fs.Length];
fs.Read(imgData, 0, imgData.Length);
}
else
{
// If the button is disabled, load the image into a Bitmap object, then run it through the grayscale filter.
using (System.Drawing.Bitmap img = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(fs))
using (System.Drawing.Bitmap imgGs = RainstormStudios.Drawing.BitmapFilter.GrayScale(img))
using(System.IO.MemoryStream imgGsStrm = new System.IO.MemoryStream())
{
imgGs.Save(imgGsStrm, img.RawFormat);
imgData = new byte[imgGsStrm.Length];
imgGsStrm.Read(imgData, 0, imgData.Length);
}
}
}
context.Response.StatusCode = 200;
context.Response.ContentType = contentType;
context.Response.OutputStream.Write(imgData, 0, imgData.Length);
}
}
示例8: FilePathComPressToByte
/// <summary>
/// FilePathComPressToByte
/// </summary>
/// <param name="filePath"></param>
/// <returns>byte[] / null</returns>
private static byte[] FilePathComPressToByte(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return null;
var fileInfo = new System.IO.FileInfo(filePath);
using (var originalFileStream = fileInfo.OpenRead())
{
if (originalFileStream.Length >= 1024*ComPressMin)
{
var fileStreamByte = FileStreamComPressToByte(originalFileStream);
if (fileStreamByte != null && fileStreamByte.Count() > 0)
{
return fileStreamByte;
}
}
else
{
return System.IO.File.ReadAllBytes(filePath);
}
}
return null;
}
示例9: startbtn_Click
private void startbtn_Click(object sender, EventArgs e)
{
try
{
string ServerName = ServerNametxt.Text;
string Database = Databasenametxt.Text;
string Username = SqlUserNametxt.Text;
string Password = SQLPasswordtxt.Text;
string env = envcombo.Text;
if (ServerName == "")
{
MessageBox.Show("Missing Server Name");
}
else if (Database == "")
{
MessageBox.Show("missing Database name");
}
else if (Username == "")
{
MessageBox.Show("missing SQL username");
}
else if (Password == "")
{
MessageBox.Show("missing SQL Password");
}
else if (env == "")
{
MessageBox.Show("Missing Environment");
}
else
{
SqlConnection myConnection = new SqlConnection("server=" + ServerName + ";database=" + Database + ";connection timeout=90;uid=" + Username + ";password=" + Password); /* for user auth add Trusted_Connection = yes; before database name*/
myConnection.Open();
SqlCommand cmd = new SqlCommand();
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[5];
string path = (@"'c:\test\" + Database + date + "_" + env + ".bak'"); /*backup file location and name*/
cmd.CommandText = ("use master BACKUP DATABASE " + Database + " to disk=" + path); /*SQL script to run a backup of the database*/
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
cmd.ExecuteNonQuery();
}
//FTP Credental
string FTPuser = FTPusertxt.Text;
string FTPpassword = FTPpasswordtxt.Text;
string FTPsite = FTPSitetxt.Text;
string FTPenv = envcombo.Text;
//FTP connection
if (FTPsite == "")
{
MessageBox.Show("Missing FTP Site");
}
else if (FTPuser == "")
{
MessageBox.Show("missing FTP user");
}
else if (FTPpassword == "")
{
MessageBox.Show("Missing FTP password");
}
else
{
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[5];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPsite + "/" + Database + date + FTPenv + ".bak");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPuser, FTPpassword);
//uploading file
System.IO.FileInfo fi = new System.IO.FileInfo(@"c:\test\" + Database + date + "_" + FTPenv + ".bak");
request.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 4069;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = request.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)request.GetResponse();
//value = uploadResponse.StatusDescription;
uploadResponse.Close();
}
MessageBox.Show("complete");
}
catch (SqlException ex)
{
MessageBox.Show("error" + ex.Message);
}
}
示例10: ResumableUppload
/// <summary>
/// DO NOT WORK - API RETURNS ALWAYS PROBLEM WITH HASH WHERE IT IS OK. USE UPLOADFILE()
/// </summary>
/// <param name="FileName"></param>
/// <param name="Upl_FolderID"></param>
/// <param name="ActionOnDuplicate"></param>
/// <param name="Path"></param>
/// <returns></returns>
public IUpload ResumableUppload(string FileName, string Upl_FolderID="", UploadDuplicateActions ActionOnDuplicate = UploadDuplicateActions.None, string Path="")
{
IPreUpload preUploadResult = PreUpload(FileName, MakeHash: true, Upl_FolderID: Upl_FolderID, ActionOnDuplicate: ActionOnDuplicate, Resumable: true, Path: Path);
if (!string.IsNullOrEmpty(preUploadResult.FileID))
{
return new Upload()
{
upload_key = preUploadResult.FileID,
result = "Success",
message = "UploadKey contains FileID"
};
}
if (preUploadResult.Resumable_upload == null)
{
return null; // error
}
if (preUploadResult.Resumable_upload.Number_of_units == 1)
{
//Normal Upload
return UploadFile(FileName, Upl_FolderID, ActionOnDuplicate: ActionOnDuplicate, Path: Path);
}
int Unit_Size = preUploadResult.Resumable_upload.Unit_size;
int Nb_Units = preUploadResult.Resumable_upload.Number_of_units;
var bitmap = MediaFireApiHelper.decodeBitmap(preUploadResult.Resumable_upload.UploadBitmap);
if (bitmap.Count != Nb_Units)
{
//Error
}
System.IO.FileInfo fi = new System.IO.FileInfo(FileName);
using (System.IO.FileStream file = fi.OpenRead())
{
byte[] buffer = new byte[Unit_Size];
for (int i = 0; i < Nb_Units - 1; i++)
{
if (!bitmap[i])
{
file.Read(buffer, 0, Unit_Size);
IUpload result = UploadFilePart(FileName, buffer, i, Upl_FolderID);
}
}
if (!bitmap[bitmap.Count - 1])
{
buffer = new byte[fi.Length - ((Nb_Units - 1) * Unit_Size)];
file.Read(buffer, 0, buffer.Length);
IUpload result = UploadFilePart(FileName, buffer, Nb_Units-1, Upl_FolderID);
}
}
return null;
}
示例11: DeserializeHashes
HashSet<string> DeserializeHashes()
{
var hashesPath = new System.IO.FileInfo(string.Format("{0}\\{1}\\imageHashes.xml",
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
System.Reflection.Assembly.GetEntryAssembly().GetName().Name));
if (hashesPath.Exists)
using (var strm = hashesPath.OpenRead())
return (HashSet<string>)_imageHashSerializer.Deserialize(strm);
else
return new HashSet<string>();
}
示例12: startbtn_Click
private void startbtn_Click(object sender, EventArgs e)
{
try
{
string ServerName = ServerNametxt.Text;
string Database = Databasenametxt.Text;
string Username = SqlUserNametxt.Text;
string Password = SQLPasswordtxt.Text;
string Directory = PathDirectorytxt.Text;
string env = envcombo.Text;
SqlConnection myConnection = new SqlConnection("server=" + ServerName + ";database=" + Database + ";uid=" + Username + ";password=" + Password + ";connection timeout=1200"); /* for user auth add Trusted_Connection = yes; before database name ;connection timeout=1200*/
if (ServerName == "")
{
MessageBox.Show("Missing Server Name.");
}
else if (Database == "")
{
MessageBox.Show("Missing Database name.");
}
else if (Username == "")
{
MessageBox.Show("Missing SQL username.");
}
else if (Password == "")
{
MessageBox.Show("Missing SQL Password.");
}
else if (env == "")
{
MessageBox.Show("Missing Environment.");
}
else if (Directory == "")
{
MessageBox.Show("Missing Directory.");
}
else
{
progressBar1.Value = 0;
progressBar1.Value += 10;
/*SqlConnection myConnection = new SqlConnection("server=" + ServerName + ";database=" + Database + ";uid=" + Username + ";password=" + Password); for user auth add Trusted_Connection = yes; before database name ;connection timeout=1200*/
myConnection.Open();
SqlCommand cmd = new SqlCommand();
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[5];
string path = ("'"+Directory + Database + date + "_" + env + ".bak'"); /*backup file location and name*/
cmd.CommandText = ("use master BACKUP DATABASE " + Database + " to disk=" + path+" WITH NOFORMAT, NOINIT, NAME = N'"+ Database +"-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 100"); /*SQL script to run a backup of the database*/
cmd.CommandType = CommandType.Text;
cmd.Connection = myConnection;
cmd.ExecuteNonQuery();
progressBar1.Value += 20;
}
//FTP Credental
string FTPuser = FTPusertxt.Text;
string FTPpassword = FTPpasswordtxt.Text;
string FTPsite = FTPSitetxt.Text;
string FTPenv = envcombo.Text;
string FTPDirectory = FTPDirectorytxt.Text;
//FTP connection
if (FTPsite == "")
{
MessageBox.Show("Missing FTP Site");
}
else if (FTPuser == "")
{
MessageBox.Show("missing FTP user");
}
else if (FTPpassword == "")
{
MessageBox.Show("Missing FTP password");
}
else if (FTPDirectory == "")
{
MessageBox.Show("Missing FTP Directory password");
}
else
{
progressBar1.Value += 30;
MessageBox.Show("SQL back up is complete, now starting to upload the file to the " + FTPsite + ".");
DateTime now = DateTime.Now;
string date = now.GetDateTimeFormats('d')[5];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPsite + "/" + Database + date + "_" + FTPenv + ".bak");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(FTPuser, FTPpassword);
progressBar1.Value += 20;
//uploading file
System.IO.FileInfo fi = new System.IO.FileInfo(FTPDirectory + Database + date + "_" + FTPenv + ".bak");
request.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 4069;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = request.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
//.........这里部分代码省略.........
示例13: PostAudioData
public void PostAudioData(string accesstoken, string accesstokensecret, string Hostname, string Externalurl, string type)
{
try
{
oAuthTumbler.TumblrConsumerKey = ConfigurationManager.AppSettings["TumblrClientKey"];
oAuthTumbler.TumblrConsumerSecret = ConfigurationManager.AppSettings["TumblrClientSec"];
var prms = new Dictionary<string, object>();
var postUrl = string.Empty;
if (type == "audio")
{
// Load file meta data with FileInfo
System.IO.FileInfo fileInfo = new System.IO.FileInfo(Externalurl);
// The byte[] to save the data in
byte[] data = new byte[fileInfo.Length];
// Load a filestream and put its content into the byte[]
using (System.IO.FileStream fs = fileInfo.OpenRead())
{
fs.Read(data, 0, data.Length);
}
// Delete the temporary file
fileInfo.Delete();
prms.Add("type", "audio");
// prms.Add("caption", body);
prms.Add("source", Externalurl);
prms.Add("data", data);
postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post";
}
KeyValuePair<string, string> LoginDetails = new KeyValuePair<string, string>(accesstoken, accesstokensecret);
string result = oAuthTumbler.OAuthData(postUrl, "POST", LoginDetails.Key, LoginDetails.Value, prms);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
示例14: PostdescriptionData
public void PostdescriptionData(string accesstoken, string accesstokensecret, string Hostname, string linkurl, string title, string description, string type)
{
try
{
oAuthTumbler.TumblrConsumerKey = ConfigurationManager.AppSettings["TumblrClientKey"];
oAuthTumbler.TumblrConsumerSecret = ConfigurationManager.AppSettings["TumblrClientSec"];
var prms = new Dictionary<string, object>();
var postUrl = string.Empty ;
if (type == "link")
{
prms.Add("type", "link");
prms.Add("title", title);
prms.Add("url", linkurl);
prms.Add("description", description);
postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post";
}
else if (type == "chat")
{
prms.Add("type", "chat");
prms.Add("title", title);
prms.Add("conversation", linkurl);
// prms.Add("dialogue", description);
postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post";
}
else if (type == "video")
{
prms.Add("type", "video");
if (string.IsNullOrEmpty(linkurl))
{
prms.Add("embed", "title");
prms.Add("caption", "description");
//System.IO.FileInfo fileInfo = new System.IO.FileInfo(title);
//byte[] data = new byte[fileInfo.Length];
//// Load a filestream and put its content into the byte[]
//using (System.IO.FileStream fs = fileInfo.OpenRead())
//{
// fs.Read(data, 0, data.Length);
//}
//// Delete the temporary file
//fileInfo.Delete();
//prms.Add("data", data);
}
else {
prms.Add("embed", "linkurl");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(linkurl);
byte[] data = new byte[fileInfo.Length];
// Load a filestream and put its content into the byte[]
using (System.IO.FileStream fs = fileInfo.OpenRead())
{
fs.Read(data, 0, data.Length);
}
// Delete the temporary file
fileInfo.Delete();
prms.Add("data", data);
}
postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post";
}
KeyValuePair<string, string> LoginDetails = new KeyValuePair<string, string>(accesstoken, accesstokensecret);
string result = oAuthTumbler.OAuthData(postUrl, "POST", LoginDetails.Key, LoginDetails.Value, prms);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
}
示例15: Run
override public async void Run()
{
//Android.Media.MediaExtractor extractor;
Android.Media.MediaCodec decoder = null;
using (var extractor = new Android.Media.MediaExtractor())
//using (Android.Media.MediaCodec decoder = null)
{
//extractor = new Android.Media.MediaExtractor();
try
{
await extractor.SetDataSourceAsync(SAMPLE).ConfigureAwait(false);
}
catch (Exception ex)
{
var s = ex.ToString();
return;
}
for (int i = 0; i < extractor.TrackCount; i++)
{
var format = extractor.GetTrackFormat(i);
Log.Debug("Format info: ", format.ToString());
String mime = format.GetString(Android.Media.MediaFormat.KeyMime);
if (mime.StartsWith("video/"))
{
Log.Debug("Format mime: ", mime);
//Log.Debug("Format " + MediaFormat.KeyMaxInputSize + ": ",
// format.GetInteger(MediaFormat.KeyMaxInputSize).ToString());
Log.Debug("Format " + MediaFormat.KeyWidth + ": ",
format.GetInteger(MediaFormat.KeyWidth).ToString());
Log.Debug("Format " + MediaFormat.KeyHeight + ": ",
format.GetInteger(MediaFormat.KeyHeight).ToString());
PrintFormatInfo(format);
extractor.SelectTrack(i);
//decoder = Android.Media.MediaCodec.CreateDecoderByType(mime);
//this is where the Xamarin Android VM dies.
//decoder.Configure(format, surface, null, 0);
break;
}
}
//if (decoder == null)
//{
// Android.Util.Log.Error("DecodeActivity", "Can't find video info!");
// return;//can't continue...
//}
var f = new Java.IO.File(dir+"decode.out");
if (f.Exists())
f.Delete();
f.CreateNewFile();
var f2 = new Java.IO.File(dir + "decode2.out");
if (f2.Exists())
f2.Delete();
f2.CreateNewFile();
//open the file for our custom extractor
var inInfo = new System.IO.FileInfo(SAMPLE);
if (!inInfo.Exists)
{
Log.Error("input file not found!", inInfo.FullName);
return;
}
using (var inStream = inInfo.OpenRead())
using (var fs2 = new Java.IO.FileOutputStream(f2))//get an output stream
using (var fs = new Java.IO.FileOutputStream(f))//get an output stream
{
//var inputBuffers = decoder.GetInputBuffers();
//var outputBuffers = decoder.GetOutputBuffers();
var info = new Android.Media.MediaCodec.BufferInfo();
bool started = false, isEOS = false;
var sw = new System.Diagnostics.Stopwatch();
long startMs = sw.ElapsedMilliseconds;
sw.Start();
byte[] peekBuf = new byte[188];
//for dumping the sample into instead of the decoder.
var buffer = Java.Nio.ByteBuffer.Allocate(165000);// decoder.GetInputBuffer(inIndex);
var buffEx = new BufferExtractor();
var tmpB = new byte[20000];
while (!interrupted)
{
//sw.Restart();
if (!isEOS)
{
int inIndex = 1;// decoder.DequeueInputBuffer(10000);
if (inIndex >= 0)
{
//.........这里部分代码省略.........